has_many:通过外键? [英] has_many :through with a foreign key?
本文介绍了has_many:通过外键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已阅读有关此问题的多个问题,但尚未找到适合我情况的答案.
I've read multiple questions about this, but have yet to find an answer that works for my situation.
我有 3 个模型:Apps
、AppsGenres
和 Genres
I have 3 models: Apps
, AppsGenres
and Genres
以下是每个字段的相关字段:
Here are the pertinent fields from each of those:
Apps
application_id
AppsGenres
genre_id
application_id
Genres
genre_id
这里的关键是我不使用这些模型中的 id
字段.
The key here is that I'm not using the id
field from those models.
我需要根据那些 application_id
和 genre_id
字段关联表格.
I need to associate the tables based on those application_id
and genre_id
fields.
这是我目前得到的,但没有得到我需要的查询:
Here's what I've currently got, but it's not getting me the query I need:
class Genre < ActiveRecord::Base
has_many :apps_genres, :primary_key => :application_id, :foreign_key => :application_id
has_many :apps, :through => :apps_genres
end
class AppsGenre < ActiveRecord::Base
belongs_to :app, :foreign_key => :application_id
belongs_to :genre, :foreign_key => :application_id, :primary_key => :application_id
end
class App < ActiveRecord::Base
has_many :apps_genres, :foreign_key => :application_id, :primary_key => :application_id
has_many :genres, :through => :apps_genres
end
作为参考,这是我最终需要的查询:
For reference, here is the query I ultimately need:
@apps = Genre.find_by_genre_id(6000).apps
SELECT "apps".* FROM "apps"
INNER JOIN "apps_genres"
ON "apps"."application_id" = "apps_genres"."application_id"
WHERE "apps_genres"."genre_id" = 6000
推荐答案
已更新试试这个:
class App < ActiveRecord::Base
has_many :apps_genres, :foreign_key => :application_id
has_many :genres, :through => :apps_genres
end
class AppsGenre < ActiveRecord::Base
belongs_to :genre, :foreign_key => :genre_id, :primary_key => :genre_id
belongs_to :app, :foreign_key => :application_id, :primary_key => :application_id
end
class Genre < ActiveRecord::Base
has_many :apps_genres, :foreign_key => :genre_id
has_many :apps, :through => :apps_genres
end
有查询:
App.find(1).genres
它生成:
SELECT `genres`.* FROM `genres` INNER JOIN `apps_genres` ON `genres`.`genre_id` = `apps_genres`.`genre_id` WHERE `apps_genres`.`application_id` = 1
并查询:
Genre.find(1).apps
生成:
SELECT `apps`.* FROM `apps` INNER JOIN `apps_genres` ON `apps`.`application_id` = `apps_genres`.`application_id` WHERE `apps_genres`.`genre_id` = 1
这篇关于has_many:通过外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文