在父母和孩子的表laravel中插入行 [英] Insert row in parents and childs table laravel

查看:76
本文介绍了在父母和孩子的表laravel中插入行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很失落.我有名为Navbar的表,模型和控制器.在这里,我创建导航栏按钮.我制作了名为"type_1"的子表.因此,导航栏"id转到表"type_1"其列称为"navbar_id".

Im so lost. I have table, model and controller named Navbar. Here I create navbar buttons. I made child table called "type_1". So "navbar" id goes to table "type_1" and its column called "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创建孩子的空行?我应该使用模型还是可以在这里使用?

Here navbar button is created. How can I create childs empty row with parent (navbar) id? Should I use models or I can do it here?

推荐答案

在您的 Parent 模型上,您需要定义如下关系:

On your Parent model, you need to define a relation like this :

public function child()
{
    return $this->hasMany(Child::class);
}

现在您可以使用雄辩的方法插入数据:

Now you can insert data with eloquent method like this :

$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' => 'me@john.com']); // here parent_id will be created by the model

创建方法的正式文档

Official documentation of the create method

这篇关于在父母和孩子的表laravel中插入行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆