I have the following table setup:
countries (id)
languages (id)
country_languages (id, country_id, language_id)
In plain SQL I can fetch all countries with their corresponding language(s) fairly easily:
SELECT * FROM countries
INNER JOIN country_languages
ON country_languages.country_id = countries.id
INNER JOIN languages
ON languages.id = country_languages.language_id;
In Laravel (5), using the following works:
In Country model:
public function countryLanguages()
{
return $this->hasMany('CountryLanguage');
}
In CountryLanguage Model:
public function language()
{
return $this->belongsTo('Language');
}
$countries = Country::with('countryLanguages.language');
I'd like have a single relationship method languages
however that can be called directly on the Country
model. Is this possible? I've tried the hasManyThrough
and other methods but so far no luck!
Thanks to geondri for pushing me in the right direction. This is what I ended up with which is a lot easier than I could possibly imagine:
public function languages()
{
return $this->belongsToMany('Language', CountryLanguage::getTableName());
}