![](/img/trans.png)
[英]Laravel Eloquent - Get Eloquent Relationship Model Data From nested Relationship
[英]Get relationship from another relationship with Eloquent and Laravel 8
我尝试使用属于 InvoiceData 的国家名称获取地址。 发票数据属于个人或企业资料。 最后一个条件是使用morphTo() Laravel 的功能。
简化的数据库结构:
personal_profiles:
id, name
invoice_data:
id, address_id, invoiceable_id, invoiceable_type
addresses:
id, country_id, postal_code, city
countries
id, name
然后模型:
class UserProfile extends Model
{
public function invoiceData()
{
return $this->morphOne(InvoiceData::class, 'invoiceable');
}
}
class InvoiceData extends Model
{
public function imageable()
{
return $this->morphTo();
}
public function address()
{
return $this->belongsTo(Address::class)->with(Country::class);
}
}
class Address extends Model
{
public function country()
{
return $this->belongsTo(Country::class);
}
}
class Country extends Model
{
public function address()
{
return $this->hasMany(Address::class);
}
}
Controller:
public function getPersonalInvoiceData()
{
/** @var User $user */
$user = \Auth::user();
/** @var UserProfile $profile */
$profile = $user->userProfile;
/** @var InvoiceData $invoiceData */
$invoiceData = $profile->invoiceData;
/** @var Address $address */
$address = $invoiceData->address;
//$address = $invoiceData->address()->with(Country::class)->get();
$responseData = [
'name' => $user->name,
'surname' => $user->surname,
'address' => $address,
];
return response()->json($responseData);
}
获取地址没有问题:
"address": {
"id": 1,
"country_id": 171,
"city": "Foo City",
"postal_code": "00-100",
}
但我不知道如何使用 Eloquent 用相关名称“替换”country_id。 如您所见,我尝试使用 with() on 但出现异常消息: Call to undefined relationship [App\\Models\\Country] on model [App\\Models\\Address]
。 我认为我提到的关系就足够了。 我忘记了什么?
您不应该在“with”中使用 class 应该有关系名称,但我认为您不想使用 with 方法,因为当您调用 get 方法时它会获取所有国家/地区。
你所要做的就是:
$address = $invoiceData->address->load('country');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.