Ad

Laravel Eloquent Pivot With Primary Id To Reference To Another Pivot

i have problem with relationship between pivot tables.

I have many to many relation between countries and streets but primary key of this (pivot table) has many to many relationship with numbers.

I need this listings (with eloquent):

$country = Country::findOrFail(1)->with('streets', 'numbers')
foreach ($country->streets as $street){
    foreach($street->numbers as $number) {
       $number;
    }
}

Or exist any solution?

This is only example. Official name of tables are changed.

Example structure:

Table Countries
    id
    name

Table Streets
    id
    name

Table country_street
   id
   country_id
   street_id

Table number_country_street
   id
   number_id
   country_street_id

Table numbers
   id
   name

Thanks for help.

Ad

Answer

IMHO with your tables I would define an additional model: CountryStreet, something like that:

// CountryStreet
class CountryStreet extends Model
{
    public function city()
    {
         return $this->belongsTo('App\City');
    }

    public function street()
    {
         return $this->belongsTo('App\Street');
    }
    public function numbers()
    {
         return $this->belongsToMany('App\Number', 'number_country_street');
    }
}

// Country
class Country extends Model
{
    public function streets()
    {
         return $this->hasManyThrough('App\Street', 'App\CountryStreet');
    }
}

// Streets
class Street extends Model
{
    public function countries()
    {
         return $this->hasManyThrough('App\Country', 'App\CountryStreet');
    }
}

// Number
class Number extends Model
{
    public function country_streets()
    {
         return $this->belongsToMany('App\CountryStreet', 'number_country_street');
    }
}
Ad
source: stackoverflow.com
Ad