我有这样设计的查询:
$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 中创建它吗?如何进行查询?
最佳答案
使用withCount()
方法:
->withCount(['tags' => function($q) {
q->where.... // Put conditionals here if needed.
}])
->orderBy('tags_count', 'desc')
If you want to count the number of results from a relationship without actually loading them you may use the
withCount
method, which will place a{relation}_count
column on your resulting models
关于php - Laravel - 查询生成器 - 按标签数量对结果进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43041826/