gpt4 book ai didi

mysql - 如何获取连接中的对象?

转载 作者:行者123 更新时间:2023-11-29 07:16:53 24 4
gpt4 key购买 nike

这是我的架构:

Mention.rb

belongs_to :user


create_table "mentions", force: :cascade do |t|
t.integer "user_id", limit: 4
t.integer "mentionable_id", limit: 4
t.string "mentionable_type", limit: 191
t.datetime "created_at"
t.datetime "updated_at"
t.datetime "deleted_at"
end

用户.rb

No Association.

查询:

mentions = Mention.joins(:user).where(mentions: {mentionable_type: 'Comment', mentionable_id: @comments_ids}).select('users.*, mentions.mentionable_id AS comment_id').group_by(&:comment_id)

输出:

=> {155=>
[#<Mention:0x00007ff51a309de8 id: 110, created_at: Thu, 07 Nov 2019 10:19:46 UTC +00:00, updated_at: Thu, 07 Nov 2019 10:19:46 UTC +00:00, deleted_at: nil>,
#<Mention:0x00007ff51a3092f8 id: 112, created_at: Thu, 07 Nov 2019 10:19:46 UTC +00:00, updated_at: Thu, 07 Nov 2019 10:19:46 UTC +00:00, deleted_at: nil>],
156=>[#<Mention:0x00007ff51a3098e8 id: 111, created_at: Thu, 07 Nov 2019 10:19:46 UTC +00:00, updated_at: Thu, 07 Nov 2019 10:19:46 UTC +00:00, deleted_at: nil>]}
输出中的

id:110user115mentionable_id

如何使用 group_by mentionable_id 获取完整的用户对象?

预期:

=> {155=>
[#<User:0x00007ff51a309de8 id: 110, name: "abc", email: 'xyz@mail.com', deleted_at: nil>,
#<User:0x00007ff51a3092f8 id: 112, name: "abc", email: 'xyz@mail.com', deleted_at: nil>],
156=>[#<User:0x00007ff51a3098e8 id: 111, name: "abc", email: 'xyz@mail.com', deleted_at: nil>]}

最佳答案

需要通过User查询:

User.joins(:mentions)
.where(mentions: { mentionable_type: 'Comment', mentionable_id: @comments_ids })
.select('users.*, mentions.mentionable_id AS comment_id')
.group_by(&:comment_id)

关于mysql - 如何获取连接中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58748290/

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