gpt4 book ai didi

mysql - ActiveRecords Rails 中的多重连接优化

转载 作者:可可西里 更新时间:2023-11-01 08:48:48 26 4
gpt4 key购买 nike

有四种模型:Car、Person、Country 和 Religion。

class Car < ActiveRecord::Base
belongs_to :person
has_one :country, through: :person
has_one :religion, through: :person

def self.get_indian_cars_owned_by_hindus
self.joins(:country).joins(:religion).where("countries.name=? and religions.name=?", 'India', 'Hindu').count
end
end

class Person < ActiveRecord::Base
belongs_to :country
belongs_to :religion
has_one :car
end

class Country < ActiveRecord::Base
has_many :persons
end

class Religion < ActiveRecord::Base
has_many :persons
end

模型汽车中的函数 get_indian_cars_owned_by_hindus 对表国家和宗教应用了一些条件。调用函数时生成的查询是这样的:

SELECT COUNT(*) FROM `cars` INNER JOIN `persons` ON `persons`.`id` = `cars`.`person_id` INNER JOIN `countries` ON `countries`.`id` = `persons`.`country_id` INNER JOIN `persons` `persons_cars_join` ON `persons_cars_join`.`id` = `cars`.`person_id` INNER JOIN `religions` ON `religions`.`id` = `persons_cars_join`.` religion_id` WHERE (`countries`.`name` = 'India') AND (`religions`.`name` = 'Hindu');

我最初希望查询是这样的:

SELECT COUNT(*) FROM `cars` INNER JOIN `persons` ON `persons`.`id` = `cars`.`person_id` INNER JOIN `countries` ON `countries`.`id` = `persons`.`country_id` INNER JOIN `religions` ON `religions`.`id` = `persons`.`religion_id` WHERE (`countries`.`name` = 'India') AND (`religions`.`name ` = '印度教');

这里的 ActiveRecords 没有优化 persons 和 cars 表之间的额外连接。虽然我相信 mysql 会在最后对其进行优化,但在 rails 方式 中正确编写它的方法是什么。

我显然可以将方法移到模型人员内部,但这不是我要寻找的解决方案。可能存在多个节点的情况。

编辑:将模型名称从 A、B、C 和 D 更改为汽车、人、国家和宗教

最佳答案

最好的办法是将 join 调用更改为不使用 has_many :through 关系。相反,您可以将深层关系嵌套在一个数组中,如下所示:

def self.get_indian_cars_owned_by_hindus
self.joins(:person => [:country, :religion]).
where("countries.name=? and religions.name=?", 'India', 'Hindu').
count
end

关于mysql - ActiveRecords Rails 中的多重连接优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20065205/

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