php - 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');
}
解决方案
可以使用whereHas完成所需的结果,如下所示:
$categories = Category::whereHas("town")->get();
我在这里假设您已经在每个类别属于城镇的类别模型上定义了 belongsTo 关系(每个城镇的反面有很多类别)。
推荐阅读
- sql - 即使sql中的一个字段为空,如何显示两列字段的总和结果?
- apache - 删除 URL 中的 index.php 时出现重定向错误
- c# - 发布 .Net Framework Web API 时找不到 XML 文档?
- ssl - Netbeans - ftp连接上的过期证书
- javascript - 如何迭代评论集合以获得所有不同级别的评论回复?
- javascript - 将不同键的值放入单个数组
- flutter - 在按钮单击时使用未来构建器刷新主页上的数据 - 颤动
- mysql - 查询从两列获取比较结果
- c++ - 如何在 Mac 中向 CLion 添加开源库?
- mysql - 节点 mysql2 无法访问更新结果