I have got 3 models associated with this question; Country, Manufacturer and Region.
I've simplified the tables for the sake of this question. I don't think anything else in the tables or any of the other models are anything to do with the problem.
My tables are set up like so;
manufacturers
- id
- name
countries
- id
- name
regions
- id
- name
- manufacturer_id
- country_id
What I want to be able to do is to write $manufacturer->countries
in my blade and have it spit out the countries that are associated with a given manufacturer.
The models are currently related to each other like this;
Country.php
public function manufacturers()
{
return $this->hasMany(Manufacturer::class);
}
public function regions()
{
return $this->hasMany(Region::class);
}
Region.php
public function manufacturer()
{
return $this->belongsTo(Manufacturer::class);
}
public function country()
{
return $this->belongsTo(Country::class);
}
and where I'm having the problem, Manufacturer.php
I think I need a hasMany relationship. I've already got;
public function regions()
{
return $this->hasMany(Region::class);
}
and I would have thought I would have needed;
public function countries()
{
return $this->hasManyThrough(Country::class,Region::class);
}
but that leads to this error;
Column not found: 1054 Unknown column 'countries.region_id' in 'on clause' (SQL: select `countries`.*, `regions`.`manufacturer_id` as `laravel_through_key` from `countries` inner join `regions` on `regions`.`id` = `countries`.`region_id` where `regions`.`manufacturer_id` = 4)
so I tried swapping the classes round to give;
public function countries()
{
return $this->hasManyThrough(Region::class,Country::class);
}
but that leads to;
Column not found: 1054 Unknown column 'countries.manufacturer_id' in 'field list' (SQL: select `regions`.*, `countries`.`manufacturer_id` as `laravel_through_key` from `regions` inner join `countries` on `countries`.`id` = `regions`.`country_id` where `countries`.`manufacturer_id` = 4)
Does anyone know how I should be setting my relationships up in order to achieve what I want?
I also tried a belongsToMany
relationship, which did bring back the countries, but multiple instances of the same country. I just want one instance of each country that appears in the regions table for any given manufacturer.