【问题标题】:Create or update rows Laravel创建或更新行 Laravel
【发布时间】:2020-03-19 11:52:37
【问题描述】:

我尝试使用请求中的数据更新或创建一个表,更新时它可以工作,但创建时我只能做 1 个。所以,如果我有 4 个新项目,只保存 1 个,不知道为什么,并且没有错误。如果我转储请求,我将拥有所有值。

$answers = new LkpAnswer;

    foreach ($request->items as $key => $item) {
        if (isset($item['id'])) {
            $answers->where('id', $item['id'])->update($item);
        } else {
            $answers->fill($item)->save();
        }
    }

【问题讨论】:

    标签: laravel laravel-6


    【解决方案1】:

    请尝试以下代码:

    foreach ($request->items as $key => $item) {
        if (isset($item['id'])) {
            LkpAnswer::where('id', $item['id'])->update($item);
        } else {
            $answers = new LkpAnswer; //new up an empty model(object) then fill it with your array of data, and finally save it.
            $answers->fill($item)->save();
        }
    }
    

    【讨论】:

    • 是的,我现在发现了这一点。我必须将新模型放在 else 中,才能使每个项目起作用。谢谢!
    【解决方案2】:

    这应该可以通过内置方法巧妙地实现:

    foreach ($request->items as $item) {
        LkpAnswer::updateOrCreate($item['id'],$item);
    }
    

    确保相关字段可填写 - 请参阅 mass assignment protection

    【讨论】:

      猜你喜欢
      • 2014-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-15
      • 2018-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多