Reputation: 29009
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
cars
setcolor
= red,energy
= 0.1,updated_at
= 2018-01-12 15:26:47 whereid
is null)
Why is he looking for
id
is null
?
Upvotes: 6
Views: 22033
Reputation: 17132
To be clear, your original syntax is correct. You can use it on a relation:
$user->car()->updateOrCreate(['idMember' => $user->id], [
'color' => 'red',
'energy' => '0.1',
]);
This will check if there is a car
with idMember === $user->id
; if so, update color
and energy
. If not, it will create a car
record with idMember
, color
, and energy
.
I haven't tested, but based on the first parameter's array type, you should be able to pass in multiple match conditions, such as
['idMember' => $user->id, 'day' => 'tuesday']
Upvotes: 13
Reputation: 2241
In your model mention the primaryKey if primarykey is not "ID"
protected $primaryKey = "Your Primary Key";
If you do not need icnrementing for your primary key
public $incrementing = false;
Thats it ..
Upvotes: -3
Reputation: 29009
This is how I solved my problem without adding an unnecessary auto incrementing id to the cars model:
class Car extends Model
{
protected $primaryKey = 'idMember';
public $incrementing = false;
Upvotes: 1
Reputation: 2725
Your cars model should have a primary key, commonly called "id". Create it.
Upvotes: 2