问题描述
我很失落。我有名为Navbar的表,模型和控制器。在这里,我创建导航栏按钮。我制作了名为“ type_1”的子表。因此,“ navbar” id进入表“ type_1”,其列称为“ navbar_id”。
$form_data = array(
'tipas' => $tipas,'p_id' => $p_id,'name' => $request->title,'text' => $request->text,'img' => $name
);
navbar::create($form_data); //created parent row
在此处创建导航栏按钮。如何创建带有父(navbar)ID的孩子的空行?我应该使用模型还是可以在这里使用?
解决方法
在您的Parent
模型上,您需要定义如下关系:
public function child()
{
return $this->hasMany(Child::class);
}
现在,您可以使用雄辩的方法插入数据:
$form_data = array(
'tipas' => $tipas,'p_id' => $p_id,'name' => $request->title,'text' => $request->text,'img' => $name
);
$q = Parent::create($form_data); //created parent row
$q->child()->create(['name' => 'John','email' => '[email protected]']); // here parent_id will be created by the model
the create method的官方文档