簡體   English   中英

如何將SQL查詢轉換為優化的Rails Active Record查詢?

[英]How to convert SQL query to optimized Rails Active Record query?

我有這個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")

但它沒有用,我曾期望它能用。

有幾件事情要解決和提出問題,使他們很難正確回答

  • 您如何在BankerOrganization之間建立關系?
  • 如之前所問:您期望什么?
  • 您是否為該軟刪除功能使用了一些gem( deleted_at is NULL )? (例如妄想症
  • 您可以提供從您的版本生成的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')

如果您對用戶和組織使用上面提到的偏執狂寶石,則*.deleted_at is not null查詢部分將被自動添加,這將ruby查詢減少了。

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

在極少數情況下,您對導軌不了解。 這是有關關聯文章的鏈接。

可能對您的情況有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM