我对透视表之间的关系有问题。
我在国家和街道之间有许多对多的关系,但是这个(数据透视表)的主键与数字有多对多的关系。
我需要这些清单(有说服力):
$country = Country::findOrFail(1)->with('streets', 'numbers')
foreach ($country->streets as $street){
foreach($street->numbers as $number) {
$number;
}
}
或者存在任何解决方案?
这只是一个例子。表的正式名称已更改。
示例结构:
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
谢谢你的帮助。
发布于 2019-03-03 13:25:07
对于您的表,我将定义一个额外的模型: CountryStreet,类似于:
// 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');
}
}
发布于 2019-03-03 17:27:56
@dparoli有个好主意。
有时对于多对多关系使用继承Pivot类,但现在无关紧要。
因此,现在我们可以将这些代码用于清单。
$country = Country::findOrFail(1);
foreach ($country->countryStreet as $countryStreet){
echo $countryStreet->street->name
foreach($countryStreet->numbers as $number) {
$number;
}
}
class Countries
public function countryStreet()
{
return $this->hasMany(CountryStreet::class, 'country_id', 'id');
}
Class CountryStreet with method block() using relation hasOne
另一个实现是up。
https://stackoverflow.com/questions/54968572
复制