【问题标题】:Getting ActiveRecord Query to work with a left outer join让 ActiveRecord Query 与左外连接一起工作
【发布时间】:2021-04-04 01:07:25
【问题描述】:

我不确定我在语法上做错了什么,希望得到帮助。一个InventoryItem 有很多MaintenanceOrders。每个MaintenanceOrder 都有一个布尔字段still_usable。从逻辑上讲,我想对所有仍然可用的InventoryItems 运行查询,这意味着它们要么根本没有任何MaintenanceOrders,要么它们的MaintenanceOrders 都没有still_usable: false 的标志。

快速Rspec

describe "test query" do
 before do
   InventoryItem.create(random_id:"a")
   InventoryItem.create(random_id:"b")
   InventoryItem.create(random_id:"c")

   InventoryItem.where(random_id:"a").last.maintenance_orders.create(still_usable:false)
   InventoryItem.where(random_id:"b").last.maintenance_orders.create(still_usable:nil)
   InventoryItem.where(random_id:"b").last.maintenance_orders.create(still_usable:true)


   @query = InventoryItem.left_outer_joins(:maintenance_orders).where.not(maintenance_orders:{still_rentable:false}).distinct
 end
 it "should return b & c" do
   expect(@query.map(&:random_id)).to match_array(["b","c"])
   # a has a maintenance order with flag still_usable:false so is excluded
   # b has maintenance orders, but none have flag still_usable:false, so is included
   # c has no maintenance orders, so is included
 end
end

【问题讨论】:

    标签: sql ruby-on-rails activerecord rails-activerecord


    【解决方案1】:

    您可以使用 SQL NOT EXISTS 实现它

    InventoryItem.where("NOT EXISTS (
       SELECT * FROM maintenance_orders 
       WHERE (maintenance_orders.inventory_item_id = inventory_items.id) 
       AND maintenance_orders.still_rentable = false)")
    

    【讨论】:

    • 这成功了!我很好奇这可以用 ActiveRecord 提供的语法来完成,还是必须使用 SQL?就像我仍然很好奇为什么我的代码在语法上是错误的并且不起作用
    • 我认为ActiveRecord没有提供任何语法。
    • 还有什么字段名是still_rentable还是still_usable
    • 我想写查询rails的方式,你也可以用NOT IN和子查询-InventoryItem.where.not(id: MaintenanceOrder.where(still_usable: false).select(:inventory_item_id))
    • 啊,好吧,写它仍然需要另一个数据库查询到 MaintenanceOrder,好的,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    • 2011-10-01
    • 2012-09-10
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多