mysql - 如何在连接中获取对象?
问题描述
这是我的架构:
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:110
这是输出中的 is ofuser
和115
is mentionable_id
。
如何使用 group_by 提及的_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)
推荐阅读
- c# - FtpWebRequest ProtocolViolationException
- python - 将数据框中的值列表附加到新列
- javascript - 如何为按钮(在网格中)提供滑动效果?
- ajax - 服务器端 Ajax 的对应物
- android - Android通过minicap拍摄快照,返回文件都是0bytes
- python - 如何在 Redis 缓存中设置值,使用 Python 由同一列名下的多行组成
- xcode - 在 SwiftUI 中动态更新列表?
- python - python 3中张量流中的多输出和多损失函数问题
- javascript - 确定 APNG 的持续时间(或帧数)
- jmeter - JMeter - 按需暂停(和恢复)执行