【问题标题】:Eloquent updateOrCreate not updating雄辩的更新或创建不更新
【发布时间】:2018-05-19 01:02:55
【问题描述】:

我在使用 updateOrCreate 时遇到问题。

下面的代码成功创建了一个新行;但是,在更新现有行时,它根本不起作用!

comm_helpful::updateOrCreate(
           ['ID' => 1],
           ['time' => 3000]
        );

这完全符合预期:

comm_helpful::where('ID', 1)->update(['time' => 3000]);

我已将上面的示例简化为最低限度(我在调试过程中这样做了),但仍然无法正常工作!!

【问题讨论】:

  • 你有什么错误吗?
  • 你收到MassAssignmentException 了吗?在您的模型中,您是否在 protected $fillable 变量中定义了用于批量赋值的字段?
  • 向我们展示您的控制器和更新表单
  • 没有错误/异常,我在模型上设置了 $fillable
  • 该模型的updating 事件是否有任何监听? fillable 中是否缺少任何字段?

标签: php laravel eloquent slim


【解决方案1】:

我也有类似的问题。 我的模型有:

protected $fillable = ['user_x_cliente_id','internet_cliente_id'];

状态为0。

              $habilita = leilao_habs::updateOrCreate(
                  [
                    'user_x_cliente_id' => $user_x_cliente->id,
                    'internet_cliente_id' => $int_cli->id
                  ],
                  ['status' => 1]
               );

               dd($habilita);

执行 updateOrCreate 后,状态仍然为 0 并且 No 出现 MassAssignmentException 错误。

解决方案是更改模型,将状态添加到受保护的 $fillable:

protected $fillable = ['user_x_cliente_id','internet_cliente_id','status'];

现在 updateOrCreate 可以改变状态。

【讨论】:

  • 虽然这通常是原因,但 OP 已经声明这不是 cmets 中的质量分配错误
【解决方案2】:

好的,在几乎完全拔掉我的头发之后;我发现了 Eloquent 设置的问题:

protected $primaryKey = 'id';

用于更新方法并由 getKeyName() 返回。

protected function setKeysForSaveQuery(Builder $query)
{

    $query->where($this->getKeyName(), '=', $this->getKeyForSaveQuery());

    return $query;
}

然后我意识到我在故事中的“id”是大写而不是小写!

我想这意味着我的回答是我需要确保我使用小写的“id”作为主键或在模型上覆盖它

protected $primaryKey = 'ID';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-30
    • 2020-12-12
    • 1970-01-01
    • 2020-12-03
    • 2013-05-31
    • 2020-02-14
    • 1970-01-01
    • 2017-04-28
    相关资源
    最近更新 更多