[英]Rails SQL: How to join belongs_to association in query that is referenced twice with two foreign keys
In my app I have an Event
model that basically represents a booking between two users.在我的应用程序中,我有一个
Event
model 基本上代表两个用户之间的预订。 It has some basic attributes about the event as well as a booker_id
and bookee_id
which both represent foreign keys from the User
table.它有一些关于事件的基本属性以及一个
booker_id
和bookee_id
,它们都表示来自User
表的外键。
Basically I am trying to put together a search method for Events that allows me to search by the booker or bookee's first and last name.基本上,我正在尝试为事件组合一个搜索方法,该方法允许我按预订者或预订者的名字和姓氏进行搜索。 But I can't figure out how to reference BOTH the
bookee
user and the booker
user in one single query.但我不知道如何在一个查询中同时引用
bookee
用户和booker
用户。 Below is my Event model showing the associations and a basic version of the Event search class method I've set up.下面是我的事件 model 显示关联和我设置的事件搜索 class 方法的基本版本。 Unfortunately, it only seems to reference the User table for Event
bookers
not bookees
.不幸的是,它似乎只引用了 Event
bookees
bookers
User 表。 I probably just need to review my SQL and write something a little uglier, but if anyone has a straightforward way to adjust that query so that it can include and reference the User
table for both bookee
users and booker
users that would be super helpful.我可能只需要查看我的 SQL 并写一些更难看的东西,但是如果有人有一种直接的方法来调整该查询,以便它可以包含和引用
bookee
用户和booker
用户的User
表,那将非常有帮助。
event.rb事件.rb
belongs_to :booker, :foreign_key => :booker_id, class_name: 'User'
belongs_to :bookee, :foreign_key => :bookee_id, class_name: 'User'
def self.search(search)
if search
search_term = "%#{search}%"
includes(:booker, :bookee).where(["users.first_name ILIKE :term OR users.last_name ILIKE :term OR event_title ILIKE :term", {term: search_term}]).references(:booker, :bookee)
end
end
user.rb用户.rb
has_many :booker_events, :foreign_key => :booker_id, class_name: 'Event', dependent: :nullify
has_many :bookee_events, :foreign_key => :bookee_id, class_name: 'Event', dependent: :nullify
You can try with a custom join trying to match those rows from the users
table where their id
is the same as the booker_id
and/or bookee_id
in the events
table:您可以尝试使用自定义联接尝试匹配
users
表中的那些行,其中他们的id
与events
表中的booker_id
和/或bookee_id
相同:
Event
.joins('INNER JOIN users ON users.id IN (events.booker_id, events.bookee_id)')
.where(
'users.last_name ILIKE :term OR
users.first_name ILIKE :term OR
event_title ILIKE :term',
term: term)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.