在 Rails 中,我有两个模型::contest
和 :problem
。每个竞赛都有很多问题,一个问题可以属于多个竞赛。不同比赛中的一个问题,可能有不同的“索引”。
我使用模型 :contest_problem
来加入 :contest
和 :problem
。在 :contest_problem
中,我有一个字段 index
,用于标记竞赛中问题的“索引”。
现在,当我执行 Contest.find(...).problems.find(...)
(...
是我想要的 racing_id 或 Problem_id查询),rails 将创建一个 sql 查询:
SELECT `problems`.*
FROM `problems`
INNER JOIN `contest_problems` ON `problems`.`id` = `contest_problems`.`problem_id`
WHERE `contest_problems`.`contest_id` = 1 AND `problems`.`id` = 1
LIMIT 1
我想执行这个sql查询:
SELECT `problems`.*, `contest_problems`.`index`
FROM `problems`
INNER JOIN `contest_problems` ON `problems`.`id` = `contest_problems`.`problem_id`
WHERE `contest_problems`.`contest_id` = 1 AND `problems`.`id` = 1
LIMIT 1
我应该在 Rails 中做什么?
<小时/>型号:
class Contest < ActiveRecord::Base
has_many :contest_problems
has_many :problems, through: :contest_problems
end
class Problem < ActiveRecord::Base
has_many :contest_problems
has_many :contests, through: :contest_problems
end
class ContestProblem < ActiveRecord::Base
belongs_to :contest
belongs_to :problem
end
迁移:
class CreateContestProblems < ActiveRecord::Migration
def change
create_table :contest_problems do |t|
t.integer :contest_id
t.integer :problem_id
t.string :index, limit: 2
t.timestamps
end
end
end
最佳答案
尝试这个查询:
Problem.includes(:contests, :contest_ problems)
.where(@problem.id)
.where(contests: { id: @contest.id } ).first
这将在一次数据库查询中为您提供所需的信息。
关于mysql - 在rails中,如何查询连接表中的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27203346/