4级laravel雄辩关系

时间:2017-02-06 07:10:08

标签: php laravel-5 eloquent

我有四张桌子,我希望建立一个4级关系。我的表看起来像这样:

------------|------------|------------|------------|
    City    |  Category  |Subcategory |   Company  |
------------|------------|------------|------------|
     id     |     id     |     id     |     id     |
    name    |    name    |    name    |    name    |
------------|------------|------------|------------|

我做了类似的事情:

City.php

 public function categories()
    {
        return $this->belongsToMany(Category::class);
    }

Category.php

public function subcategories()
{
    return $this->belongsToMany(Subcategory::class);
}

Subcategory.php

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

但它没有给出我需要的结果。我有许多城市可以根据他们的类别和子类别拥有许多公司。例如,我可以将city_id,category_id,subcategory_id保存到公司表中,并让正确的公司进行查询:

 $company->where('city_id', 1)->where('category_id', 2)->where('subcategory_id', 3)->get();

但我认为这不是最佳做法。我希望有人帮忙。感谢。

主要问题是如何从此查询中建立正常关系:

我有很多城市可以有很多类别,有很多子类别,子类别我有特定城市的公司 - > category->子类别。

例如,在 Company 模型中,我有 city_id, category_id, subcategory_id ,当我为特定的类别提取时城市子类别子类别 companies 。 因此查询将类似于:

App\Company::where('city_id', 1)->where('category_id', 2)->where('subcategory_id, 3)->get();

抱歉说不好。我希望你能得到它......

0 个答案:

没有答案
相关问题