在Rails中,如何在Rails中创建以下查询?我知道如何用SQL编写它。我会知道是否可以使用滑轨。
以下代码:
one_day_ago = 1.days.ago.at_beginning_of_day;
Client.joins(:user => {:cart => [:cart_items, :saved_items]}).where('cart_items.created_at > ?', one_day_ago).group('clients.user_id')
上面的代码创建以下查询:
SELECT `clients`.* FROM `clients`
INNER JOIN `users` ON `users`.`id` = `clients`.`user_id`
INNER JOIN `carts` ON `carts`.`user_id` = `users`.`id`
INNER JOIN `cart_items` ON `cart_items`.`cart_id` = `carts`.`id`
AND `cart_items`.`type` IN ('CartItem')
INNER JOIN `cart_items` `saved_items_carts` ON `saved_items_carts`.`cart_id` = `carts`.`id`
AND `saved_items_carts`.`type` IN ('SavedItem')
WHERE (cart_items.created_at > '2019-03-31 04:00:00.000000') GROUP BY clients.user_id
如何获取Rails来创建这样的查询:
选择clients
。*在clients
上从users
内部联接users
。id
= clients
。user_id
carts
上的carts
内部联接。user_id
= users
。id
cart_items
上的cart_items
内部联接。cart_id
= carts
。id
在哪里(cart_items.created_at>'2019-03-31 04:00:00.000000'
AND cart_items.type IN('SavedItem','CartItem'))GROUP BY clients.user_id
答案 0 :(得分:1)
我不确定您为什么要让第二部分具有OR,但是您可以根据需要编写连接查询:
Client.joins(user: { cart: [:cart_items] }).joins("INNER JOIN cart_items saved_cart_items ON saved_cart_items.cart_id = carts.id OR saved_cart_items.type IN ('SavedItem')").where('cart_items.created_at > ?', one_day_ago).group('clients.user_id')
查看此更新的查询是否为您提供所需的输出:
Client
.joins(:user, :cart)
.joins('INNER JOIN cart_items ON cart_items.id = carts.id')
.where('cart_items.created_at > ?', one_day_ago)
.where(cart_items: { type: ['SavedItem', 'CartItem'] })
.group('clients.user_id')