首页 > 解决方案 > Laravel Eloquent 仅从地点中提取类别

问题描述

我想仅使用特定城镇中存在的类别(俱乐部、酒吧等类别)创建一个数组

我已经在控制器中编写了这段代码,该控制器使用视图所需的数据获取城镇:

    $town = Town::where('identifier', $town)->with(['places' => function($q) {
        $q->with('location')->with('categories')->with('minimum');
    }])->withCount('places')->first();

如何仅使用此查询中存在的类别创建数组?

**编辑

镇上有很多地方,地方属于很多类别。

城镇模型:

   public function places()
    {
        return $this->hasMany(Place::class);
    }

放置模型:

public function town() {
    return $this->belongsTo(Town::class);
}

public function categories() {
    return $this->belongsToMany(PlaceCategory::class, 'place_place_category');
}

地方类别模型:

public function places() {
    return $this->belongsToMany(Place::class, 'place_place_category');
}

标签: phplaraveleloquent

解决方案


可以使用whereHas完成所需的结果,如下所示:

$categories = Category::whereHas("town")->get();

我在这里假设您已经在每个类别属于城镇的类别模型上定义了 belongsTo 关系(每个城镇的反面有很多类别)。


推荐阅读