Ad

Laravel Orm Not Save Relation Key And Child Model

- 1 answer

I would like to save data through Eloquent, in particular an Object and its respective Address. The Object has inside an id_address which should be updated following the creation of the Address. But this does not happen. Although it is following the guide code and the mapping of the relationships in the models is correct.

That's the code in my controller Object:

$obj= new Object(['alias' => $curr['alias']]);
$obj->save();
$address= new Address(['address'=>$curr['address']['city']]);
$obj->address()->associate($address);
$obj->save();

relation in models Object:

public $belongsTo = [
        'address' => [
                '\XXXXXX\Models\Address',
                'key'=>'id_address',
                'otherKey'=>'id',
                'delete'=>true
        ],

relation in address model:

public $hasOne = [
        'obj' => [
                '\XXXXXXX\Models\Object',
                'key'=>'id',
                'otherKey'=>'id_address',
                'delete'=>false
        ]
];

Why is created only the object and not the address and the id_address in object table?

Ad

Answer

$address= new Address(['address'=>$curr['address']['city']]);

This will instantiate an Address object, but it will not save in db. So that object doesn't have an id and that's why the id_address (btw I strongly suggest you to change the field name to address_id) is not updated.

You should do

$address= new Address(['address'=>$curr['address']['city']]);
$address->save();
$obj->address()->associate($address);

Anyway it doesn't make sense to save your Object twice, just save it after the associate() call.

Ad
source: stackoverflow.com
Ad