gpt4 book ai didi

mysql - 如何将 SQL 查询转换为优化的 Rails Active Record 查询?

转载 作者:行者123 更新时间:2023-11-29 07:05:00 25 4
gpt4 key购买 nike

我有一个 SQL 查询,当我运行它时它可以正常工作,但是我如何表示它并通过 ActiveRecord 获取相同的数据?

select concat(o.code, ' - ', u.name) 
from users u join user_organizations uo on u.id = uo.user_id
join organizations o on uo.organization_id = o.id
where u.approved = true
and u.deleted_at is null
and o.deleted_at is null
and u.type = 'Banker'
order by o.code asc;

我试过了

Banker.joins(:user_organizations => :organization)
.where(:approved => true)
.select("concat(organizations.code, users.name)")
.order("organizations.code asc")

但它没有起作用,而我原以为它会起作用。

最佳答案

有一些事情需要解决和提出问题,因此很难正确回答

  • 银行家组织之间的关系如何?
  • 如前所述:您期待什么?
  • 您是否使用一些 gem 来实现此软删除功能(deleted_at 为 NULL)? (例如paranoia)
  • 您能提供从您的版本生成的 SQL 查询吗?

我假设你的设置看起来像这样

class User < ApplicationRecord
has_and_belongs_to_many :organizations
end

class Organization < ApplicationRecord
has_and_belongs_to_many :users
end

如果是这样,您应该能够执行以下操作

User.select("concat(organizations.code, ' - ', users.name)")
.includes(:organizations)
.where('users.deleted_at is not null')
.where('organizations.deleted_at is not null')
.where('users.type = ?', 'Banker')
.order('organizations.code ASC')

如果您为用户和组织使用上面提到的 paranoia gem,将自动添加 *.deleted_at is not null 查询部分,从而将 ruby​​ 查询减少到这样的程度。

User.select("concat(organizations.code, ' - ', users.name)")
.includes(:organizations)
.where('users.type = ?', 'Banker')
.order('organizations.code ASC')

在极少数情况下,您不了解 rails 。这是 article about associations 的链接.

关于mysql - 如何将 SQL 查询转换为优化的 Rails Active Record 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42062469/

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