[英]Laravel belongsTo nested or belongsTo through
國家:街道 1:N
城市:街道 1:N
class City extends Model
{
public function country()
{
return $this->belongsTo(Country::class);
}
}
class Street extends Model
{
public function city()
{
return $this->belongsTo(City::class);
}
public function country()
{
return ...
}
}
我只需要加載國家關系,沒有城市
Street::with('country')->where('id', $id)->first();
喜歡
{
"id": 1,
"name": "abbey road",
"country": {
"id": 2,
....
您的Street
model 不需要country()
關系,除非您的streets
表具有country_id
。 您可以簡單地鏈接關系:
$street = Street::with('city.country')->where('id', $id)->first();
這將返回您的Street
model,並加載相關的City
和Country
。 您可以通過$street->city->country
訪問Country
:
$street = Street::with('city.country')->where('id', $id)->first();
$country = $street->city->country; // `Country: {'id' => 2, 'name' => '...'}`
如果您希望能夠訪問$street->country
,則需要一個訪問器:
class Street extends Model {
public function getCountryAttribute(){
return $this->city->country;
}
}
然后,可以使用速記:
$street = Street::with('city.country')->where('id', $id)->first();
$country = $street->country; // `Country: {'id' => 2, 'name' => '...'}`
據我所知,Laravel 中沒有belongsToThrough()
關系,但鏈式關系就足夠了。
您可以為此使用 hasOneThrough 關系
public function country()
{
return $this->hasOneThrough(
Country::class,
City::class,
'country_id', // Foreign key on cities table...
'id', // Foreign key on owners table...
'city_id', // Local key on streets table...
'id' // Local key on city table...
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.