gpt4 book ai didi

ruby-on-rails-3 - 导轨 : ActiveRecord Query for has_many :through model

转载 作者:行者123 更新时间:2023-12-04 07:06:41 25 4
gpt4 key购买 nike

如何查询具有“has_many :through”关系的某个分支的公司?

  #company.rb
has_many :branch_choices
has_many :branches, :through => :branch_choices

“查找所有分支机构 ID 为 3 的公司”

最佳答案

Company.includes(:branches).where(:branches => {:id => 3})

或者
Branch.find(3).companies

更新
实际上,第一个代码段有一个缺点:它急切地将分支机构与公司一起加载。为了避免这种开销,您可以考虑使用左连接:
Company.
joins("LEFT JOIN `branch_choices` ON `branch_choices`.`company_id` = `companies`.`id`").
where(:branch_choices => {:branch_id => 3})

关于ruby-on-rails-3 - 导轨 : ActiveRecord Query for has_many :through model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6890903/

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