php - Post 模型与城市和国家的关系(来自 Location 模型)
问题描述
我有一个Post
模型和一个Location
模型。我已经设置了多对多关系,以便通过引入中间表来工作$post->getCities
。$location->getPosts
这是位置表:
现在,我想做的是获取属于一个国家的所有帖子?这对我拥有的现有表和关系是否可行?
解决方案
如果你$post->getCities
看起来像那样
return $this->hasMany(Location::class, ...);
然后 QueryBuilder 返回,允许您在执行对数据库的请求之前以随意的方式过滤查询:
$post->getCities()->where('country', $yourCountry)->get();
否则,如果您$post->getCities
已经返回一个集合,您可以在集合上应用where方法并在应用程序一侧对其进行过滤:
$locations = $post->getCities(...);
$locationsByCountry = $locations->where('country', $youtCountry);
推荐阅读
- flutter - 是否可以将 onTap 与 FirebaseAnimatedList 一起使用
- bash - 是否需要 `;;` 来关闭 bash 中的“所有”案例部分?
- sql - 多列之间相互关联的分组标识符/值
- discord - Discord.py 如何使我的函数循环?
- ocaml - OCaml 遍历二维列表
- android - 如何使用 Tensorflow lite 实时计算对象?
- sparql - 如何在 sparql 中查询个人及其对象属性(使用耶拿)
- haskell - 我们如何将 Haskell 元组匹配到 Agda 数据类型?
- r - R 错误:依赖项 'xml2'、'httr' 不可用于包(Linux Mint 20.1)
- azure-iot-central - 如何通过 mqtt 将遥测数据发送到 IoT Central 中的第二个组件?