Laravel,不使用 foreach 插入多行
Laravel, insert multiple rows without using foreach
$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
中进行保存,是否可以在一行中进行保存?
只需将数组的数组传递给 Eloquent::insert()
:
$data = [];
foreach($input['activities'] as $activity_id) {
$data[] = [
'activity_id' => $activity_id,
'user_id' => Auth::id()
];
}
Coder::insert($data);
我找到了解决方案,
$activities = array(3,2,5);
$user->activities()->sync($activities);
用户模型将具有如下活动功能,
public function activities()
{
return $this->belongsToMany('App\Activity', 'user_activities')->select(['activities.id'])->withTimestamps();
}
$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
中进行保存,是否可以在一行中进行保存?
只需将数组的数组传递给 Eloquent::insert()
:
$data = [];
foreach($input['activities'] as $activity_id) {
$data[] = [
'activity_id' => $activity_id,
'user_id' => Auth::id()
];
}
Coder::insert($data);
我找到了解决方案,
$activities = array(3,2,5);
$user->activities()->sync($activities);
用户模型将具有如下活动功能,
public function activities()
{
return $this->belongsToMany('App\Activity', 'user_activities')->select(['activities.id'])->withTimestamps();
}