laravel - Spatie 查询生成器过滤嵌套关系
问题描述
使用 Spatie Query Builder 我想扩展嵌套关系的过滤器
以下代码使用工作正常的关系作业计数获取位置。我想将工作关系的过滤器扩展为可以查询多对多的关系 job.level。我怎么去?
过滤器看起来像/options/?filter[job.level]=2
德国 - 12, 意大利 - 34
$locations = QueryBuilder::for(JobLocation::class)
->select('id as value', 'title', 'country_id')
->orderBy('title')
->withCount(['job as counts' => function ($q) {
$q->whereNull('deleted_at');
}])
->whereHas('country', function ($q) {
$q->where('id', '=', 80);
})
->allowedAppends(
'job',
)
->allowedIncludes('job', 'job.level',)
->allowedFilters([
AllowedFilter::exact('job.language_id'),
AllowedFilter::exact('job.level', 'job.level.id')
])->get();
解决方案
我认为您正在寻找 whereHas 功能。请参阅此处查询关系存在的文档。但是你已经在为国家关系这样做了,这没有什么不同。
所以我认为你的看起来像:
$locations = QueryBuilder::for(JobLocation::class)
->select('id as value', 'title', 'country_id')
->orderBy('title')
->withCount(['job as counts' => function ($q) {
$q->whereNull('deleted_at');
}])
->whereHas('country', function ($q) {
$q->where('id', '=', 80);
})
//New query constraint here
->whereHas('job', function ($q) {
$q->where('level', '=', 2);
})
->allowedAppends(
'job',
)
->allowedIncludes('job', 'job.level',)
->allowedFilters([
AllowedFilter::exact('job.language_id'),
AllowedFilter::exact('job.level', 'job.level.id')
])->get();
推荐阅读
- java - 使用 FirestoreUI 实现搜索
- python - 如何使用 pymupdf 减小修改后 PDF 的大小
- python - 对编码/解码字符串感到困惑。在尝试实施 base64 之前如何进行?
- sql - 在 BigQuery 中,如何汇总匹配相同日期和 ID 的字段?
- amazon-web-services - aws 弹性负载均衡器和限制
- function - 如果将 RawMaterial 与 Textspan 或识别器一起使用,颤振将函数传递给无状态小部件不起作用
- r - ggplot facet_wrap 出错:错误:`scale_id` 不能是 `NA`
- git - VSCode:如何在版本控制下保留一些但不是全部的项目设置?
- html - 如何删除css flex中的最后一个空白空间
- scala - Spark Sql 查询在 Scala 中花费了更长的时间