我很失落。我有名为 Navbar 的表、模型和 Controller 。在这里我创建了导航栏按钮。我制作了名为“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
此处已创建导航栏按钮。如何使用父级(导航栏)id 创建子级空行?我应该使用模型还是可以在这里进行?
最佳答案
在您的Parent
模型上,您需要定义如下关系:
public function child()
{
return $this->hasMany(Child::class);
}
现在您可以使用如下的 eloquent 方法插入数据:
$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' => '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="264b43664c494e480845494b" rel="noreferrer noopener nofollow">[email protected]</a>']); // here parent_id will be created by the model
the create method的官方文档
关于laravel - 在 parent 和 child 表中插入行 laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64425572/