【问题标题】:Laravel Eloquent how to get relationship self object?Laravel Eloquent 如何获取关系自我对象?
【发布时间】:2021-09-11 15:58:46
【问题描述】:

我有以下关系的表

我的 HousingAdvertisement 模型有

public function nearPlaces()
{
    return $this->hasMany(HousingAdNearPlace::class);
}

和 HousingAdNearPlace

public function nearPlace()
{
    return $this->hasOne(NearPlace::class, 'id');
}

当我这样查询时:

HousingAdvertisement::with('nearPlaces.nearPlace')->where('user_id', '=', auth()->user()->id)->get();

我在 HousingAdvertisement 模型中得到了 HousingAdNearPlace 对象:

[...
{
...,
"near_places": [
        {
            "id": 27,
            "housing_advertisement_id": 48,
            "near_place_id": 3,
            "created_at": "2021-06-29T12:23:35.000000Z",
            "updated_at": "2021-06-29T12:23:35.000000Z",
            "near_place": null
        },
        {
            "id": 28,
            "housing_advertisement_id": 48,
            "near_place_id": 4,
            "created_at": "2021-06-29T12:23:35.000000Z",
            "updated_at": "2021-06-29T12:23:35.000000Z",
            "near_place": null
        }
    ]
...]

我怎样才能得到像这样的自己的 NearPlace 模型:

[...
{
...,
"near_places": [
        {
            "id": 3,
            "name": "Park",
            "slug": "park",
            "created_at": "2021-06-29T06:25:57.000000Z",
            "updated_at": "2021-06-29T06:25:57.000000Z"
        },
        {
            "id": 4,
            "name": "Beach",
            "slug": "beach",
            "created_at": "2021-06-29T06:25:57.000000Z",
            "updated_at": "2021-06-29T06:25:57.000000Z"
        }
    ]
...]

【问题讨论】:

标签: php laravel laravel-5 laravel-8


【解决方案1】:

您需要使用 laravel 模型访问器从 HousingAdvertisement 的名称行生成 slug

为了那个用途-

public function slug()

    {
        return Str::lower($this->name);
    }

这将从 name 属性生成一个 slug。将其添加到您的 HousingAdvertisement 模型中。现在您需要使用查询生成器对其进行转换。

为了那个用途-

protected $casts = [
    'slug' => 'string',
];

将此添加到您的 HousingAdvertisement 模型中。最后,您可以查询您的数据库,例如 -

HousingAdvertisement::find(auth()->user()->id)->get(['id', 'name', 'slug', 'created_at', 'updated_at']);

【讨论】:

    【解决方案2】:

    您需要HousingAdvertisement 上的“Has Many Through”关系

    public function nearPlaces()
    {
        return $this->hasManyThrough(NearPlace::class, HousingAdNearPlace::class);
    }
    

    并且还定义 id 键,如在文档中:https://laravel.com/docs/8.x/eloquent-relationships#has-many-through-key-conventions

    【讨论】:

      猜你喜欢
      • 2017-06-04
      • 1970-01-01
      • 1970-01-01
      • 2013-12-14
      • 2017-01-12
      • 2017-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多