Insert row in parents and childs table laravel

。_饼干妹妹 提交于 2021-01-27 20:29:20

问题


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

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?


回答1:


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



来源:https://stackoverflow.com/questions/64425572/insert-row-in-parents-and-childs-table-laravel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!