Wednesday, April 12, 2017

Laravel / Eloquent - Foreign key always NULL

I have to classes of type Model, WptModel and CacheModel.

use Model;

class CacheModel extends Model {

    use \October\Rain\Database\Traits\Validation;

    public $timestamps = false;

    public $rules = [];

    public $table = 'cache';


    public $belongsTo = [
        'WptModel' => [ 'Models\WptModel' ]
    ];

    public $incrementing = FALSE;

}

use Model;

class WptModel extends Model {

    use \October\Rain\Database\Traits\Validation;

    public $timestamps = false;

    public $rules = [];

    public $table = 'wpt';

    public $hasOne = [
        'CacheModel' => [ 'Models\CacheModel' ]
    ];

    public $belongsTo = [
        'GpxModel' => [ 'Models\GpxModel' ]
    ];

    public $incrementing = FALSE;

}

For both models I use firstOrNew to build them.

$wptmodel = WptModel::firstOrNew($values);
$cachemodel = CacheModel::firstOrNew($values);

This works like a charm. but when I try to store $cachemodel in $wptmodel and to save $gpxmodel like this:

$wptmodel->CacheModel = $cachemodel;
$gpxmodel->WptModel = $wptmodel;
$gpxmodel->save();

The following error message appears:

"SQLSTATE[23000]: Integrity constraint violation: 1048 Column
'wpt_model_id' cannot be null (SQL: update 
cache` set `wpt_model_id` =  where cache`.`wpt_model_id`
= 978a1287-3cad-4580-9c95-8ee2ed13b836 and 
cache`.`wpt_model_id` is not null)" on line 
662 of laravel/framework/src/Illuminate/Database
/Connection.php

Another thing I won't understand is that is process works for the first time (that means I'm able to insert a row into table cache). The error shows up when I execute these statements the second time (update won't work). If I have a look into the corresponding tables than it looks like that every thing is there. All columns have their values. There is definitifly no NULL-value. So I don't understand why Laravel says that _wpt_model_id_ is NULL.

Thanks in advance for your help.

fw.



via user865294

Advertisement