表格:
divisions
id name
districts
id division_id name
subdistricts
id district_id name
class Division extends Model
{
//
public function districts()
{
return $this->hasMany('App\District', 'division_id');
}
public function subdistricts()
{
// what will be here
}
}
是否可以通过division_id获取子区域而不使用subdistricts表上的division_id
答案 0 :(得分:3)
了解hasManyThrough()
关系。因此,subdisctricts()
将如下所示:
public function subdisctricts()
{
return $this->hasManyThrough('App\SubDistrict', 'App\District');
}
答案 1 :(得分:0)
您可以按照建议使用hasManyThrough()
,hasManyThrough的语法是:
class Division extends Model
{
public function posts()
{
return $this->hasManyThrough(
'App\Subdistrict', 'App\District',
'country_id', 'user_id', 'id'
);
}
}
第三个参数是foreign key on the intermediate model
的名称,第四个参数是foreign key on the final model
的名称,第五个参数是local key
- See Docs < / p>
答案 2 :(得分:0)
您需要使用hasManyThrough来表示此关系。
public function subdisctricts()
{
return $this->hasManyThrough('App\Subdistrict', 'App\District');
}
答案 3 :(得分:-1)
您可以尝试hasManyThrough()
:
public function subdistricts()
{
return $this->hasManyThrough('App\Subdistrict', 'App\District');
}
has-many-through
关系为通过中间关系访问远距离关系提供了方便的捷径。