简体   繁体   English

如何在Laravel中按大多数重复项对我的查询进行排序?

[英]How to order my query by most duplicates in 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. 为此有4个表, images表, images_tag数据透视表, tag表,当然还有users表。

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? 这可能吗?

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. 为此,您将需要join images_tagsimages表,计算标签数量,并按这些标签排序。

$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. 如果only_full_group_by选项被禁用,则以上查询仅在MySQL中only_full_group_by Otherwise, you're going to need to either rewrite this to use a sub query, or do the ordering in the returned Laravel Collection . 否则,您将需要重写此代码以使用子查询,或者在返回的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();   
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM