douya2006 2017-09-25 22:53
浏览 130
已采纳

如何在Laravel中的大多数重复项中查询我的查询?

On my website, users can post images.

Images can have tags.

There's 4 tables for this, the images table, the images_tag pivot table, the tag table, and of course the users table.

A user can have multiple images with the same tag(s).

I can pull up the tags a user has used across all his images with this query:

$userTags = Tag::whereHas('images', function($q) use($user) {
    $q->where('created_by', $user->id);
})->get();

However, I want to make it so that I can order these tags based on how frequently a user uses them. In other words, I want to order by duplicates. Is this possible?

  • 写回答

1条回答 默认 最新

  • dpgua04022 2017-09-25 23:16
    关注

    To achieve this, you're going to need to join the images_tags and images tables, count the number of tags, and order by those tags.

    $tags = Tag::selectRaw('tags.*, COUNT(images.id) AS total')
        ->join('images_tags', 'tags.id', '=', 'images_tags.tag_id')
        ->join('images', 'images.id', '=', 'images_tags.image_id')
        ->where('images.created_by', $user->id)
        ->groupBy('tags.id')
        ->orderBy('total', 'desc')
        ->get();
    

    The above query will only work in MySQL if the only_full_group_by option is disabled. Otherwise, you're going to need to either rewrite this to use a sub query, or do the ordering in the returned Laravel Collection. For example:

    $tags = Tag::selectRaw('tags.*, COUNT(images.id) AS total')
        ->join('images_tags', 'tags.id', '=', 'images_tags.tag_id')
        ->join('images', 'images.id', '=', 'images_tags.image_id')
        ->where('images.created_by', $user->id)
        ->groupBy('tags.id')
        ->get();
    
    $tags = $tags->sortByDesc(function ($tag) {
        return $tag->total; 
    });
    

    If you want to add this to your user model, per your comment, create a function similar to the following:

    public function getMostUsedTags($limit = 3)
    {
        return Tag::selectRaw('tags.*, COUNT(images.id) AS total')
            ->join('images_tags', 'tags.id', '=', 'images_tags.tag_id')
            ->join('images', 'images.id', '=', 'images_tags.image_id')
            ->where('images.created_by', $this->id)
            ->groupBy('tags.id')
            ->orderBy('total', 'desc')
            ->limit($limit)
            ->get();   
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看