Laravel:在关系上更新或创建? [英] Laravel: UpdateOrCreate on Relation?

查看:84
本文介绍了Laravel:在关系上更新或创建?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户拥有一辆汽车.

用户

id | name
1  | Bob
2  | Alice

汽车

idMember |  color  |  energy
   1     |  blue   |    0.95

在我拥有的 User 类中

public function car()
{
  return $this->hasOne('App\Car','idMember');
}

我想像这样在关系模型上调用updateOrCreate:

I want to call updateOrCreate on the relation Model like this:

$user->car()->updateOrCreate(['idMember' => $user->id], ['color' => 'red', 'energy' => '0.1']); 

但是,我收到错误消息

"SQLSTATE [42S22]:找不到列:1054'where中的未知列'id' 子句"(SQL:更新cars设置color =红色,energy = 0.1, updated_at = 2018-01-12 15:26:47其中id为空)

"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: update cars set color = red, energy = 0.1, updated_at = 2018-01-12 15:26:47 where id is null)

他为什么要寻找

id为空

?

推荐答案

这是我解决问题的方法,而没有在汽车模型中添加不必要的自动递增ID:

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;

这篇关于Laravel:在关系上更新或创建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆