gpt4 book ai didi

mysql - has_many 通过不同的外键

转载 作者:行者123 更新时间:2023-11-30 00:56:10 27 4
gpt4 key购买 nike

我正在尝试从 EventView.promoter_id = User.id 的用户获取事件,但它无法正常工作。这是我的设置(目前不正确):

User
has_many :events
has_many :promoted_event_views, :foreign_key => :promoter_id, :class_name => "EventView"
has_many :promoted_events, :through => :event_views, :foreign_key => :promoter_id #foreign key seems to be getting ignored

EventView
belongs_to :event
belongs_to :promoted_event, :class_name => "Event", :foreign_key => :event_id
belongs_to :promoter, :foreign_key => :promoter_id, :class_name => "User"

数据库设置为:

User
id
..etc (irrelevant)

Event
id
user_id
...etc (irrelevant)

EventView
id
user_id
event_id
promoter_id
...etc (irrelevant)

我正在尝试调用:

User.all.first.promoted_events

它有效,但它给了我错误的信息!它与 EventViews 上的promote_id(我想要的)无关,而是在事件上使用 user_id

这是数据库中发生的情况:

User Load (0.2ms)  SELECT `users`.* FROM `users` ORDER BY `users`.`id` ASC LIMIT 1
Event Load (2.1ms) SELECT `events`.* FROM `events` INNER JOIN `event_views` ON `events`.`id` = `event_views`.`event_id` INNER JOIN `events` `events_promoted_events_join` ON `event_views`.`event_id` = `events_promoted_events_join`.`id` WHERE `events_promoted_events_join`.`user_id` = 1

很明显, .user_id = 1 导致了问题,如何将其更改为promote_id = 1?我已经尝试在用户模型中设置primary_key和foreign_key,但它似乎被忽略了。

另外:我尝试使用 finder_sql,但它在 Rails 4 中已弃用

最佳答案

User
has_many :events
has_many :promoted_event_views, :foreign_key => 'promoter_id'
has_many :event_views
has_many :promoted_events, :through => :event_views, :source => :promoted_event

EventView
belongs_to :user
belongs_to :promoted_event, :class_name => "Event", :foreign_key => 'event_id'
belongs_to :promoter, :foreign_key => 'promoter_id', :class_name => 'User'

关于mysql - has_many 通过不同的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20529107/

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