[英]Laravel: UpdateOrCreate on Relation?
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:我想像这样在关系模型上调用 updateOrCreate :
$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) "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: updatecars
setcolor
= red,energy
= 0.1,updated_at
= 2018-01-12 15:26:47 whereid
is空)
Why is he looking for他为什么要找
id
is nullid
为空
? ?
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
;这将检查是否有car
有idMember === $user->id
; if so, update color
and energy
.如果是这样,更新color
和energy
。 If not, it will create a car
record with idMember
, color
, and energy
.如果没有,它将创建一个带有idMember
、 color
和energy
的car
记录。
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']
Your cars model should have a primary key, commonly called "id".您的汽车模型应该有一个主键,通常称为“id”。 Create it.创建它。
This is how I solved my problem without adding an unnecessary auto incrementing id to the cars model:这就是我在不向汽车模型添加不必要的自动递增 id 的情况下解决我的问题的方法:
class Car extends Model
{
protected $primaryKey = 'idMember';
public $incrementing = false;
In your model mention the primaryKey if primarykey is not "ID"在您的模型中,如果主键不是“ID”,请提及主键
protected $primaryKey = "Your Primary Key";
If you do not need icnrementing for your primary key如果您的主键不需要 icnrementing
public $incrementing = false;
Thats it ..就是这样..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.