加入不能正常工作

时间:2014-09-21 15:11:35

标签: ruby-on-rails ruby-on-rails-4

我得到了以下SQL,我正在尝试将其转换为活动记录查询方法

我有以下表格

Customers (id, name)
CustomerPriceRelations (customer_id, sales_price_id) # jointable
SalesPrices (id, margin)
ProductSalesPrices (product_id, sales_price_id) # jointable

我试图执行以下查询

SELECT sp.id, sp.margin_percentage
                    FROM sales_prices sp
                    LEFT OUTER JOIN carrier_product_Sales_Prices ps
                        ON sp.id = ps.sales_price_id
                    LEFT OUTER JOIN Customer_Price_Relations cr
                        ON ps.sales_price_id = cr.sales_price_id
                    LEFT OUTER JOIN Customers c
                        ON cr.customer_id = c.id
                    WHERE c.id = 2 AND ps.carrier_product_id = 3

我试过使用连接方法,但结果从来没有加入过某些原因,有什么帮助吗?

SalesPrice.joins(:carrier_products, :customers).where(customer_id: 2, carrier_product_id: 3)

1 个答案:

答案 0 :(得分:0)

连接()的Rails标准行为是INNER JOIN而不是LEFT OUTER JOIN。 INNER JOIN意味着,除非匹配,否则连接的两侧都不会出现任何内容。如果要使用LEFT OUTER JOIN,则需要明确定义它:

SalesPrice.joins("LEFT OUTER JOIN carrier_product_Sales_Prices ps ON sales_prices.id = ps.sales_price_id").
           joins("LEFT OUTER JOIN Customer_Price_Relations cr ON ps.sales_price_id = cr.sales_price_id").
           joins("LEFT OUTER JOIN Customers c ON cr.customer_id = c.id").
           where("cr.customer_id = ? and carrier_product_id = ?", 2, 3)