php - Laravel - 查询生成器 - 按标签数量对结果进行排序

标签 php laravel tags

我有这样设计的查询:

 $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/

相关文章:

java - 在 Spring 中替换类别的标签系统 - Hibernate java 项目

php - 选择包含变量且 ID 相同的数据组

php - Laravel 会记住 http 测试期间的原始响应

laravel - 传递给 Illuminate\\Database\\Query\\Builder::cleanBindings() 的参数 1 必须是数组类型,给定的字符串

ruby-on-rails - act_as_taggable 未定义方法 'each' 错误

php - 去除所有 HTML 标签,允许的除外

php - 通知 Ajax/Javascript 后台 PHP 已完成

php - 传递给 Illuminate\Database\Grammar::parameterize() 的参数 1 必须是数组类型,字符串给定

laravel - 在 Laravel 中,我应该将非公开的 data.json 文件放在哪个文件夹中?

php - Laravel 寻找其他迁移