$input['activities'] = array(3,2,5);
foreach($input['activities'] as $activity_id){
$user_activities = new User_activities;
$user_activities->activity_id = $activity_id;
$user_activities->user_id = Auth::id();
$user_activities->save();
}
是否可以使用单行脚本为Laravel中的每个语句执行上述操作?
而不是在foreach
中进行保存,是否可以在一行中进行保存?
答案 0 :(得分:5)
只需将数组数组传递给Eloquent::insert()
:
$data = [];
foreach($input['activities'] as $activity_id) {
$data[] = [
'activity_id' => $activity_id,
'user_id' => Auth::id()
];
}
Coder::insert($data);
答案 1 :(得分:2)
我找到了解决方案,
$activities = array(3,2,5);
$user->activities()->sync($activities);
用户模型的活动功能如下,
public function activities()
{
return $this->belongsToMany('App\Activity', 'user_activities')->select(['activities.id'])->withTimestamps();
}