如何使用Rails创建此查询?

时间:2019-04-01 18:08:43

标签: mysql ruby-on-rails

在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内部联接usersid = clientsuser_id carts上的carts内部联接。user_id = usersid cart_items上的cart_items内部联接。cart_id = cartsid 在哪里(cart_items.created_at>'2019-03-31 04:00:00.000000' AND cart_items.type IN('SavedItem','CartItem'))GROUP BY clients.user_id

1 个答案:

答案 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')