I have four tables and i want to make a 4 level relationship. My table looks like this:
------------|------------|------------|------------|
City | Category |Subcategory | Company |
------------|------------|------------|------------|
id | id | id | id |
name | name | name | name |
------------|------------|------------|------------|
I did something like this:
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);
}
But it's not giving the result I need. I have many cities that can have many companies by their category and subcategories. For example I can save city_id, category_id, subcategory_id to company table and get the right companies doing the query:
$company->where('city_id', 1)->where('category_id', 2)->where('subcategory_id', 3)->get();
But I think it's not a best practice. I hope somebody helps. Thanks.
The main question is how can i make a normal relationship from this query:
I have many Cities that can has many categories that has many Subcategories and the subcategories i have companies for the specific city->category->subcategory.
For example in Company
model i have city_id, category_id, subcategory_id
and when i'm fetching categories for the specific city there will subcategories and in subcategories will be companies
. So the query will be something like:
App\Company::where('city_id', 1)->where('category_id', 2)->where('subcategory_id, 3)->get();
Sorry for bad explanation. I hope you get it...