Laravel 5.2多模型保存()

9

我需要通过表格一次性存储恰好三个页面。我希望以与model save()方法类似的方式保存,因为这将自动更新记录时间戳。

如何同时处理多个记录?

我的页面模型:

namespace App;
use Illuminate\Database\Eloquent\Model;

class Page extends Model{
     protected $table = 'simple_pages';
}

我的代码:

public function createPages(Request $request){ // I use Page at the top
     $data = [
          [
          'title'=> $request->first,
          'content'=> $request->firstCont
          ],[
          'title'=> $request->second,
          'content'=> $request->secondCont
          ][
          'title'=> $request->third,
          'content'=> $request->thirdCont
          ]
     ];
     Page::unguard();
     $pages = new Page($data);
     $pages->save(); // Something like this would be amazing
     Page::reguard();
}

注意:我强烈反对创建多个页面模型实例,然后循环保存它们。此外,我不想使用DB插入,因为它不会自动更新记录时间戳。


2
我知道这是一个老问题,但解决方案是Page::insert($data)。请参考此答案:https://dev59.com/Al0a5IYBdhLWcg3w-9Da#29723968 - Soulriser
4个回答

5

经过长时间的搜索,看起来我找到了这个:

        $eloquentCollection->each(function ($item, $key) {
            $item->save();
        });

是的,这是迭代法,但似乎没有其他方法可以保存多个模型。唯一的替代方法是使用 DB::insert(),但要注意没有自动更新时间戳。

此外,如果您希望保存过多的 Eloquent 模型,请通过块保存它们,以避免可能出现的内存问题(或将它们推入 Queue 中)。


在更新的 Laravel 版本(自 5.4 版开始)中,您可以将其缩短为:$eloquentCollection->each->save(); - rissom

4

我找到了最佳解决方案来实现:

User::create([多个用户详细信息数组的数组])

以避免需要执行和添加条目一样多的查询

允许Eloquent一次保存多个记录


2

如果你阅读过大规模分配的手册。

public function createPages(Request $request){ // I use Page at the top
     $data = [
          [
          'title'=> $request->first,
          'content'=> $request->firstCont
          ],[
          'title'=> $request->second,
          'content'=> $request->secondCont
          ][
          'title'=> $request->third,
          'content'=> $request->thirdCont
          ]
     ];

     Page::unguard();
     $pages = Page::create($data);
     Page::reguard();
}

谢谢您的回答。我已经阅读了官方文档,但对我没有帮助。Page::create($data)会创建一个异常(preg_match()期望第二个参数为字符串,但给出了数组); 我还尝试了Page::create([...第一...],[...第二...],[...第三...]),但它只会将单个空记录插入到数据库中,这不是我想要实现的目标。 - Fusion
但是如果你的列没有在 protected $fillable = [] 中列出,它将不起作用。如果你已经设置了 $fillable 并且你的数组已经设置好了,你需要确保你的值实际上是字符串而不是数组。例如:$request->first$request->firstCont - Ash
我使用了model的unguard()和reguard()方法。因此,在这里guarded/fillable不应该是一个问题(或者说它是吗?- 如果是一个问题,Laravel会抛出mass assignment异常)。我对我的请求内容非常确定,最近使用dd()进行了检查。它们全部都是字符串。 - Fusion
@Fusion true,“Unguard”会使$fillable无关紧要,我忽略了这一点。查看create,它通过__constructfill,也许你可以调试一下这个? - Ash

0
$data = [
      [
      'title'=> $request->first,
      'content'=> $request->firstCont
      ],[
      'title'=> $request->second,
      'content'=> $request->secondCont
      ][
      'title'=> $request->third,
      'content'=> $request->thirdCont
      ]
 ];

foreach($data as $page) {
      Page::create($page);
    }

应该解决你的问题

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接