Angular-一次保存到两个(2)模型中

时间:2019-05-17 14:43:31

标签: angular laravel api

我想使用Angular7创建动态菜单和子菜单,并从Laravel获取端点。

  1. 我要同时保存到两个表中,还将main_menu表的ID传递到sub_menu

  2. 当数据保存到Menu表中时,它将传递Menu表的ID并将其传递到Sub_menu表的menu_id

Laravel:菜单控制器

Element

Laravel:子菜单控制器

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'descriptions' => 'required', 
        ]);

        $mainmenu = Mainenu::create($request->all());

        return response()->json([
            'message' => 'Great success! New Menu Item created',
            'mainmenu' => $mainmenu
        ]);
    }

角度:模型

    public function store(Request $request)
    {
        $request->validate([
            'menu_id' => 'required',
            'parent_id' => 'required'  
        ]);

        $submenu = Submenu::create($request->all());

        return response()->json([
            'message' => 'Great success! New Menu Item created',
            'submenu' => $submenu
        ]);
    }

Service.ts

export class Menu {
    id: number = '';
    name: string = '';
    description : string = '';
}

export class Submenu {
    id: number = '';
    menu_id: number = '';
    parent_id : number = '';
}

我不知道该怎么做

我想同时保存到两个表中,并且还将main_menu表的ID作为menu_id传递到sub_menu中。

1 个答案:

答案 0 :(得分:0)

您只需要使用observer

首先,您可以像这样请求

id: number = '';
name: string = '';
description : string = '';
parent_id: number = ''; //If it needs to be a submenu

在菜单控制器上:

public function store(Request $request)
{
    $request->validate([
        'name' => 'required',
        'descriptions' => 'required', 
    ]);

    $mainmenu = Mainmenu::create($request->except(['parent_id']));

    return response()->json([
        'message' => 'Great success! New Menu Item created',
        'mainmenu' => $mainmenu
    ]);
}

Observer上:

namespace App\Observers;

use App\Mainmenu;
use App\Submenu;

class MainmenuObserver
{
    /**
     * Handle the Mainmenu "created" event.
     *
     * @param  \App\Mainmenu  $mainmenu
     * @return void
     */
    public function created(Mainmenu $mainmenu)
    {
        $submenu = Submenu::create([
            'menu_id' => $mainmenu->id,
            'parent_id' => request()->parent_id
        ]);
    }
}