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
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
Ad