想设置三张表的eloquent关系

Want to setup eloquent relationship among the three tables

我在 Laravel 8 上与 Jetstream - Livewire,想要在三个 table 之间建立 eloquent 关系。即类别、Sub-Category 和菜单项。 1 个类别有很多 sub-categories,而 1 sub-category 只有 1 个类别。 1 sub-category 有很多菜单项,而 1 个菜单项只有 1 sub-category。我应该如何进行以下操作,主要是根据上述关系我想在单个 blade 视图中创建具有所有三个 table 的 CRUD 功能,请指导我。请检查下面的 table。

Category Table
-----------------------
id
category_name

Sub Category Table
-----------------------
id
category_id
sub_category_name

Menu Item Table
-----------------------
id
sub_category_id
item_name
item_description

对于Category:这是one-to-many self-referencing关系。

sub-categories 不需要单独的 table。只需 Category table.

即可轻松管理

您的 Category table 架构可能如下所示:

id
category_title
category_id (default: null)

其中 category_id 是某个类别的父级。

category_id 是自身的外键(类别 table)。因此 self-refrencing 关系。默认情况下它设置为 null,这意味着它是根父元素并且没有父元素。

示例:

id       category_title                category_id (or parent_id)

1        Welcome Drinks On Arrival       null
2        Essentials                       1
3        Mocktails                        1

作为您当前的结构,关系如下所示

类别Table

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'fillable_values_here'
    ];

    public function subCategories() {
        return $this->hasMany(SubCategory::class, 'category_id');
    }

    public function menus() {
        return $this->hasManyThrough(
            'Menu::class',
            'SubCategory::class',
            'category_id',
            'sub_category_id'
        );
    }
}

子类别模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class SubCategory extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'fillable_values_here'
    ];

    public function category() {
        return $this->belongsTo(Category::class, 'category_id');
    }

    public function menus() {
        return $this->hasMany(Menu::class, 'sub_category_id');
    }
}

菜单模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Menu extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'fillable_values_here'
    ];

    public function subCategory() {
        return $this->belongsTo(SubCategory::class, 'sub_category_id');
    }
}

有什么不明白的,尽管问。并阅读 docs 关于 Laravel 关系。