四表查询

Four tables query

我想通过一次查询从四个 table 中获取所有数据。我的 tables

类别

id

name

子类别

id

name

categories_subcategories

id

category_id

subcategory_id

id

name

category_subcategory_id

一个产品可以在一个类别和子类别中,我有类别和子类别之间的查询,想添加到这个项目table。

namespace App;

use Illuminate\Database\Eloquent\Model;

class Subcategory extends Model
{
    protected $fillable = [
        'id',
        'name',
    ];

    protected $table = 'subcategories';


    public function categoriesTwoLevel()
    {
        return $this->belongsToMany(CategoriesTwoLevel::class, 'categories_subcategories', 'subcategories_id','categories_id');
    }
}


class Categories extends Model
{
    protected $fillable = [
        'id',
        'name',
    ];

    protected $table = 'categories_two_level';

    protected $timestamp = false;

    public function subcategory()
    {
        return $this->belongsToMany(Subcategory::class, 'categories_subcategories', 'categories_id', 'subcategories_id')->withPivot('id');
    }

}

这是通过 table categories_subcategories

从子类别和类别 table 中获取所有数据的查询
CategoriesTwoLevel::with('subcategory')->get();

但是 tables 项没有可用。

使用dot notation to load nested relationships数据:

Categories::with('subcategory.categoriesTwoLevel.items')->get();

如果您正确定义了所有这些关系,这将起作用。