[英]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_tags
和images
表,计算标签数量,并按这些标签排序。
$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.