要在Laravel中加入多重创建吗?

时间:2019-02-10 09:37:09

标签: laravel-5 sql-insert jointable

我想一次在3个表中插入新记录。有没有使用一个创建或联接三个表的解决方案?

在SingleController.php中:

$single = Single::create([
                    'structure_id' => $request->structure_id,
                    'user_id' => auth()->id(),
                ]);

$structure = Structure::create([
                    'name' => $request->name,
                ]);

$placement = Placement::create([
                    'structure_id' => $request->structure_id,
                    'seed' => $request->seed,
                ]);

在Structure.php模型中:

public function singles()
{
    return $this->hasMany(Single::class);
}

public function placements()
{
    return $this->hasMany(Placement::class);
}

1 个答案:

答案 0 :(得分:1)

创建Structure后,您可以这样:

$structure->singles()->create({
    'structure_id' => $request->structure_id,
    'user_id' => auth()->id(),
})

$structure->placements()->create({
    'structure_id' => $request->structure_id,
    'seed' => $request->seed,
})

遵循Docs