Created
April 1, 2014 11:58
-
-
Save jhjguxin/9912538 to your computer and use it in GitHub Desktop.
how rails organization join query and sort them
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class WxUser < ActiveRecord::Base | |
has_many :orders, -> { order('id DESC') } | |
acts_as_follower | |
has_many :shop_wx_user_maps | |
belongs_to :shop | |
def orders_in_shop(shop_id) | |
orders.where(shop_id: shop_id) | |
end | |
def current_cart | |
carts.last || carts.new | |
end | |
def self.by_paid_count(shop_id) | |
# http://stackoverflow.com/questions/3141463/inner-join-with-count-on-three-tables | |
%( | |
SELECT | |
wx_users.*, count(orders.id) AS order_num | |
FROM wx_users | |
INNER JOIN shop_wx_user_maps ON wx_users.id = shop_wx_user_maps.wx_user_id | |
INNER JOIN orders ON orders.wx_user_id = wx_users.id | |
WHERE | |
orders.shop_id = #{shop_id} AND orders.status IN (1, 2, 3) | |
GROUP BY | |
wx_users.id | |
ORDER BY | |
order_num DESC | |
) | |
select('wx_users.*', 'count(orders.id) AS order_num').joins(:shop_wx_user_maps, :orders).where("orders.shop_id = #{shop_id} AND orders.status IN (1, 2, 3)").group("wx_users.id").order("orders.id DESC") | |
end | |
def self.by_paid_amount(shop_id) | |
# http://stackoverflow.com/questions/3141463/inner-join-with-count-on-three-tables | |
%( | |
SELECT | |
DISTINCT(wx_users.id), wx_users.*, SUM(orders.amount) AS order_amount | |
FROM wx_users | |
INNER JOIN shop_wx_user_maps ON wx_users.id = shop_wx_user_maps.wx_user_id | |
INNER JOIN orders ON orders.wx_user_id = wx_users.id | |
WHERE | |
orders.shop_id = #{shop_id} AND orders.status IN (1, 2, 3) | |
GROUP BY | |
wx_users.id | |
ORDER BY | |
order_amount DESC | |
) | |
select('DISTINCT(wx_users.id)', 'wx_users.*', 'SUM(orders.amount) AS order_amount').joins(:shop_wx_user_maps, :orders).where("orders.shop_id = #{shop_id} AND orders.status IN (1, 2, 3)").group("wx_users.id").order("orders.id DESC") | |
end | |
def self.by_paid_date(shop_id) | |
# http://stackoverflow.com/questions/3141463/inner-join-with-count-on-three-tables | |
%( | |
SELECT | |
wx_users.* | |
FROM wx_users | |
INNER JOIN shop_wx_user_maps ON wx_users.id = shop_wx_user_maps.wx_user_id | |
INNER JOIN orders ON orders.wx_user_id = wx_users.id | |
WHERE | |
orders.shop_id = #{shop_id} AND orders.status IN (1, 2, 3) | |
GROUP BY | |
wx_users.id | |
ORDER BY | |
orders.id DESC | |
) | |
joins(:shop_wx_user_maps, :orders).where("orders.shop_id = #{shop_id} AND orders.status IN (1, 2, 3)").group("wx_users.id").order("orders.id DESC") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment