Laravel Eloquent 如何获取关系自身对象?

Laravel Eloquent how to get relationship self object?

我有以下关系的表

我的 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"
        }
    ]
...]

您需要 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

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

为此使用 -

public function slug()

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

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

为此使用 -

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

将此添加到您的 HousingAdvertisement 模型中。最后你可以像 -

一样查询你的数据库
HousingAdvertisement::find(auth()->user()->id)->get(['id', 'name', 'slug', 'created_at', 'updated_at']);