Laravel在没有循环的情况下将对象附加到多对多关系中

时间:2017-11-15 02:03:25

标签: php laravel eloquent

我在用户模型和通知模型上有多对多的关系。

要创建通知并附加到许多用户,我目前正在做:

$users = User::all();
$notification = new Notification(['title'=>'some title', 'body'=>'notification body']);
$notification->save();
foreach ($users as $user) {
   $user->notifications()->attach([$notification->id]);
}

如果$users->count()成为一个非常大的数字,那么foreach实现将不是理想的; 如果没有这么多循环,请有更好的方法来完成这项工作吗?

由于

3 个答案:

答案 0 :(得分:1)

没有,没有使用Eloquent。

同时存在attach多个记录的功能,但内部使用循环本身,因此您不会在那里进行任何保存。

$notification->users()->attach([
    1 => [],
    2 => [],
    // ...
]);

在处理大型结果集时,Eloquent不一定是理想的解决方案。您可以考虑使用数据库查询构建器甚至原始SQL来处理批量插入操作。

答案 1 :(得分:1)

见这里:https://laravel.com/docs/5.4/eloquent-relationships#updating-many-to-many-relationships

您可以将id数组传递给attach()方法,如下所示:

$user_ids = User::pluck('id');
$notification = new Notification(['title'=>'some title', 'body'=>'notification body']);
$notification->save();
$notification->users()->attach($user_ids);

假设您$notification的关系当然叫users()

答案 2 :(得分:0)

$users = User::all();

$notification = Notification::create([
    'title'=>'some title', 
    'body'=>'notification body'
]);

$notification->user()->attach($users);
相关问题