我的查询设计如下:
$tags = auth()->user()->tags->toArray();
return $this->posts($request)->whereHas('tags', function ($q) use ($tags) {
$q->where(function ($q) use ($tags) {
foreach ($tags as $tag) {
$q->orWhere('tags.tag', 'like', $tag["tag"]);
}
})->select(DB::raw('count(distinct tags.id)'));
})->paginate(perPage());
SQL可以是:
select * from `posts`
where `posts`.`deleted_at` is null
and `expire_at` >= '2017-03-26 21:23:42.000000'
and (
select count(distinct tags.id) from `tags`
inner join `post_tag` on `tags`.`id` = `post_tag`.`tag_id`
where `post_tag`.`post_id` = `posts`.`id`
and (`tags`.`tag` like 'PHP' or `tags`.`tag` like 'pop' or `tags`.`tag` like 'UI')
) >= 1
但是我需要按照帖子中的标签数量来排序结果,那么应该是这样的:
select p.*
from posts p
join (
select pt.post_id,
count(distinct t.id) as tag_count
from tags t
inner join post_tag pt on t.id = pt.tag_id
where t.tag in ('PHP', 'pop', 'UI')
group by pt.post_id
) pt on p.id = pt.post_id
where p.deleted_at is null
and p.expire_at >= '2017-03-26 21:23:42.000000'
order by pt.tag_count desc;
是否可以在Laravel中创建它?如何完成查询?
答案 0 :(得分:2)
使用withCount()
方法:
->withCount(['tags' => function($q) {
q->where.... // Put conditionals here if needed.
}])
->orderBy('tags_count', 'desc')
如果您想要计算关系中的结果数而不实际加载它们,您可以使用
withCount
方法,这会在生成的模型上放置{relation}_count
列