首页 > 解决方案 > Post 模型与城市和国家的关系(来自 Location 模型)

问题描述

我有一个Post模型和一个Location模型。我已经设置了多对多关系,以便通过引入中间表来工作$post->getCities$location->getPosts这是位置表:

在此处输入图像描述

现在,我想做的是获取属于一个国家的所有帖子?这对我拥有的现有表和关系是否可行?

标签: phplaravel

解决方案


如果你$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);

推荐阅读