gpt4 book ai didi

mysql - rails : Joining tables and grouping by count

转载 作者:行者123 更新时间:2023-11-29 01:56:39 25 4
gpt4 key购买 nike

我是 Rails 的新手,目前正在研究一个标记系统,我可以在其中为事件分配多个标签,并将相同的标签分配给多个事件。

标签模型如下所示:

has_many :taggings,
has_many :events, through: :taggings

事件模型如下所示:

belongs_to :user
has_many :taggings
has_many :tags, through: :taggings

我有三个这样的表:

TAGS
id | name (string)

EVENTS
id | name (string)

TAGGINGS
id | tag_id | event_id

现在我正在尝试获取前 10 个最常用的标签。我基本上需要将 taggings 和 tags 表连接在一起,并在 taggings 中按 tag_id 分组。像这样:

Tagging.group('tag_id').order('count_id DESC').limit(10).count('id')

但是,通过加入标签,我可以获取名称字段。

最佳答案

试试这个:

Tag.select('tags.*, COUNT(taggings.id) AS tagging_count').
joins(:taggings).group('tags.id').
order('tagging_count DESC').
limit(10).pluck(:name)

关于mysql - rails : Joining tables and grouping by count,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27102689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com