Mysql 在rails中,如何查询联接表中的字段?
在rails中,我有两个模型,Mysql 在rails中,如何查询联接表中的字段?,mysql,sql,ruby-on-rails,Mysql,Sql,Ruby On Rails,在rails中,我有两个模型,:contest和:problem。每个竞赛都有许多问题,一个问题可以属于许多竞赛。一个问题在不同的比赛中,可能有不同的“指数” 我使用model:contest\u problem加入:contest和:problem。在:竞赛\问题中,我有一个字段索引,用于标记竞赛中问题的“索引” 现在,当我执行Contest.find(…).problems.find(…)(…是我要查询的竞赛id或问题id)时,rails将创建一个sql查询: SELECT `problem
:contest
和:problem
。每个竞赛都有许多问题,一个问题可以属于许多竞赛。一个问题在不同的比赛中,可能有不同的“指数”
我使用model:contest\u problem
加入:contest
和:problem
。在:竞赛\问题
中,我有一个字段索引
,用于标记竞赛中问题的“索引”
现在,当我执行Contest.find(…).problems.find(…)
(…
是我要查询的竞赛id或问题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
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
我要执行此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
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
class CreateCompetingProblems
尝试此查询:
Problem.includes(:contests, :contest_ problems)
.where(@problem.id)
.where(contests: { id: @contest.id } ).first
这将在一个数据库查询中为您提供所需的信息