Laravel使用非数组变量

时间:2016-04-14 20:50:53

标签: php mysql laravel orm eloquent

您好我有一个表(项目)可以分配多个用户。在创建新项目时,我需要将所选用户插入到包含用户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。

1 个答案:

答案 0 :(得分:0)

你可以像这样进行大量插入。

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