laravel - 在 parent 和 child 表中插入行 laravel

标签 laravel row parent

我很失落。我有名为 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/

相关文章:

mysql - 通过 Laravel 迁移创建/使用存储过程

php - Foreach inner When 查询 Laravel

java - 将行添加到 jTable

sql - 在 MySQL 中获取表的行数?

javascript - 使用 jQuery 根据输入值为子元素添加类

php - Laravel 4 Ajax 检查以包含 XMLHttpRequest(来自 Magnific Popup)

php - 如何选择表格的某些列?

ruby - 将一行(数组)添加到空矩阵

mysql - MS Access 2010 基于父字段过滤可重复使用的子表单

jQuery 检测上述未知级别的父级?