jeudi 1 octobre 2015

Laravel 5 model relationship many to many

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!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire