1

Whenever i create a relationship entry into the parent model it doesn't seem to set the foreign_key.

Example:

$vehicle = Vehicle::create([ 'vin'       => $data['VIN'],
                             'engine'    => $data['ENGINE'],
                             'style'     => $data['STYLE'] 
]);

$relationship = $vehicle->owner()
                 ->firstOrCreate([ 'name'      => $name,
                                   'age'       => $age,
                                   'gender'    => $gender,
                                   'addr_id'   => $address->id 
]);

This will create a new vehicle with the four attributes id, vin, engine and style and if not existing already a new Owner with the 5 attributes id, name, age, gender and addr_id.

But the owner_id in the vehicle tables stays "null". I thought creating it this was would automaticle set the owner_id on the vehicle table. Of course i could now update the vehicle and insert the $relationship->id to the vehicle.owner_id.

But then i wouldn't have to use relationships at all and could simply call:

$relationship = Owner::firstOrCreate([ 'name'      => $name,
                                       'age'       => $age,
                                       'gender'    => $gender,
                                       'addr_id'   => $address->id 
]);

and would have the same situation.

I even tried stuff like $vehicle->owner()->save($relationship); But the owner_id always stays null. Otherwise calling it with existing data for reading works.

Any ideas?

morxw
  • 13
  • 3
  • It will work with create() method ```$roleData = array( 'name' => 'Admin', 'description' => 'Admin Role', 'active' => true ); $role = Role::create($roleData); // created a new role here $role->user()->create(['name' => 'Albert', 'email' => 'albert@gmail.com']); // place the following method in role model public function user() { return $this->hasMany(User::class); }``` – Albert Sep 14 '22 at 11:59

0 Answers0