A user hasOne car.
users
id | name
1 | Bob
2 | Alice
cars
idMember | color | energy
1 | blue | 0.95
Inside the User class I have
public function car()
{
return $this->hasOne('App\Car','idMember');
}
I want to call updateOrCreate on the relation Model like this:
$user->car()->updateOrCreate(['idMember' => $user->id], ['color' => 'red', 'energy' => '0.1']);
However, I get the error message
"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: update
carssetcolor= red,energy= 0.1,updated_at= 2018-01-12 15:26:47 whereidis null)
Why is he looking for
idis null
?
id, having a primary key is also a relational requirement (though it may be a composite key which laravel does not support). Just save your sanity and add an auto incrementingidcolumn in that table so everything has a unique id. Also by convention laravel expects the foreign key to be<singular other table>_idi.e. in your caseidMembershould beuser_id(but you can change that in yourhasOneparameters)primaryKeyof my car model since no AI key is needed in a hasOne relation.