gpt4 book ai didi

php - Laravel插入多条记录,带有非数组变量

转载 作者:行者123 更新时间:2023-11-29 21:08:08 25 4
gpt4 key购买 nike

您好,我有一个表(项目),可以为其分配多个用户。创建新项目时,我需要将选定的用户插入到链接表中,其中包含用户的 id 和创建的 project_id。

    $project = new Project;
$project->project_name = $request->project_name;
$project->expected_start_date = $request->expected_start_date;
$project->expected_end_date = $request->expected_end_date;
$project->project_desc = $request->project_desc;
$project->client_id = $request->client_id;
$project->save();

foreach($request->user_id as $user){
$link_project_user = new link_project_user;
$link_project_user->user_id = $user;
$link_project_user->project_id = $project->id;
$link_project_user->save();
}

目前,我正在创建项目并通过 $project->id 获取 id,然后循环遍历所选用户并为每个用户创建一个新用户。

然而,这似乎效率稍低,因为理论上这会对数据库进行多次查询。实现上述插入的最有效和最佳的方法是什么。

我最初尝试传递一组用户,但这需要一组项目 ID。

最佳答案

您可以像这样进行批量插入。

$project = new Project;
$project->project_name = $request->project_name;
$project->expected_start_date = $request->expected_start_date;
$project->expected_end_date = $request->expected_end_date;
$project->project_desc = $request->project_desc;
$project->client_id = $request->client_id;
$project->save();

$lpus = [];

foreach($request->user_id as $user){
$link_project_user["user_id"] = $user;
$link_project_user["project_id"] = $project->id;
$lpus[] = $link_project_user;
}

link_project_user::insert($lpus);

关于php - Laravel插入多条记录,带有非数组变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36633739/

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