【问题标题】:Get relationship from another relationship with Eloquent and Laravel 8从另一个与 Eloquent 和 Laravel 8 的关系中获取关系
【发布时间】:2023-03-10 06:18:01
【问题描述】:

我尝试使用属于 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);
    }
}

和控制器:

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]。我认为我提到的关系就足够了。我忘记了什么?

【问题讨论】:

    标签: laravel eloquent foreign-keys


    【解决方案1】:

    您不应该在“with”中使用类,应该有关系名称,但我认为您不想使用 with 方法,因为当您调用 get 方法时它会获取所有国家/地区。

    你所要做的就是:

    $address = $invoiceData->address->load('country');
    

    【讨论】:

      猜你喜欢
      • 2015-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-21
      • 1970-01-01
      • 1970-01-01
      • 2015-01-29
      • 2015-04-10
      相关资源
      最近更新 更多