创建或更新Laravel行

时间:2020-03-19 11:52:37

标签: laravel laravel-6

我尝试使用请求中的数据更新或创建表,更新后它可以工作,但是在创建时我只能执行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();
        }
    }

2 个答案:

答案 0 :(得分: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();
    }
}

答案 1 :(得分:0)

这应该可以通过内置方法轻松实现:

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

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