【问题标题】:Laravel - query builder - sort results by amount of tagsLaravel - 查询构建器 - 按标签数量对结果进行排序
【发布时间】:2017-03-27 08:49:32
【问题描述】:

我有这样设计的查询:

 $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 中创建它?怎么查询?

【问题讨论】:

    标签: php laravel tags


    【解决方案1】:

    使用withCount() 方法:

    ->withCount(['tags' => function($q) {
        q->where.... // Put conditionals here if needed.
    }])
    ->orderBy('tags_count', 'desc')
    

    如果您想在不实际加载关系的情况下计算结果的数量,您可以使用withCount 方法,该方法将在结果模型上放置一个{relation}_count

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-30
      • 1970-01-01
      • 2012-07-14
      相关资源
      最近更新 更多