gpt4 book ai didi

mysql - Laravel,插入多行而不使用foreach

转载 作者:行者123 更新时间:2023-12-01 00:09:50 24 4
gpt4 key购买 nike

$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);

关于mysql - Laravel,插入多行而不使用foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29604039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com