ruby-on-rails Rails活动记录:通过指向同一列的多个自定义关联连接单个表

368yc8dk  于 2023-05-23  发布在  Ruby
关注(0)|答案(1)|浏览(111)

我正尝试通过多个自定义关联加入同一个表。
我的模型有以下关联,

class Order < ApplicationRecord
  belongs_to :advertiser, class_name: 'Account'
  belongs_to :facilitator, class_name: 'Account'
  belongs_to :creator, class_name: 'Account'

如何使用Active Record和/或Arel创建以下SQL查询?(不仅仅是直接提供SQL字符串)

INNER JOIN accounts ON accounts.id = orders.facilitator_id
OR accounts.id = orders.creator_id
OR accounts.id = orders.advertiser_id

我试过以下几种方法,

Order.joins(:advertiser, :facilitator, :creator)

但得到了以下结果

SELECT `orders`.*
FROM `orders`
INNER JOIN `accounts` ON `accounts`.`id` = `orders`.`advertiser_id`
INNER JOIN `accounts` `facilitators_orders` ON `facilitators_orders`.`id` = `orders`.`facilitator_id`
INNER JOIN `accounts` `creators_orders` ON `creators_orders`.`id` = `orders`.`creator_id`
yftpprvb

yftpprvb1#

您需要指定has_many关系Account模型的外键。

class Order < ApplicationRecord
  belongs_to :advertiser, class_name: 'Account'
  belongs_to :facilitator, class_name: 'Account'
  belongs_to :creator, class_name: 'Account'
end

Account模型中

class Account < ApplicationRecord
   has_many :advertisers,  foreign_key: 'advertiser_id', class_name: 'Order'
   has_many :facilitators, foreign_key: 'facilitator_id', class_name: 'Order'
   has_many :creators,     foreign_key: 'creator_id', class_name: 'Order'
end

类似的问题可能也有帮助!Multiple Associations With the Same Table rails

相关问题