SELECT rs.id as rs_id,
sum(rs.amount_per_month) as rs_am1,
sum(rs.amount_per_month_per_sqft) as rs_am2,
rs.from_date,rs.to_date,cc.charge_type as cc
FROM lease_rent_rolls as lrr
INNER JOIN leases as l ON lrr.lease_id = l.id
INNER JOIN rents as r ON l.id = r.lease_id
INNER JOIN rent_schedules as rs ON r.id = rs.rent_id
INNER JOIN charge_codes as cc ON rs.charge_code_id = cc.id
WHERE lrr.id = 449443
AND DATE(NOW()) BETWEEN rs.from_date AND rs.to_date
GROUP BY cc.charge_type
我在使用find_by_sql
的模型中使用此SQL查询,但我应该在Ruby连接中获得相同的结果,其中模型中的条件没有SQL的帮助。
答案 0 :(得分:1)
如果您提供关联,那么提供解决方案会更有帮助。
现在,我正在考虑:
LeaseRentRoll有一个或多个租约。
租赁有很多租金。
租金有很多rent_schedules。
和RentSchedule有很多charge_codes。
如果LeaseRentRoll有一个租约:
LeaseRentRoll.where(:id => 449443).first.lease.joins(:rents => [:rent_schedules => charge_codes]).select("rent_schedules.id as rs_id, sum(rent_schedules.amount_per_month) as rs_am1, sum(rent_schedules.amount_per_month_per_sqft) as rs_am2,
rent_schedules.from_date,rent_schedules.to_date,charge_codes.charge_type as cc“)
如果LeaseRentRoll有很多租约:
LeaseRentRoll.where(:id => 449443).first.leases.joins(:rents => [:rent_schedules => charge_codes]).select("rent_schedules.id as rs_id, sum(rent_schedules.amount_per_month) as rs_am1, sum(rent_schedules.amount_per_month_per_sqft) as rs_am2, rent_schedules.from_date,rent_schedules.to_date,charge_codes.charge_type as cc")
请查看附件图片。它将有助于更多地了解上述查询。
答案 1 :(得分:1)
RentSchedule.joins([{:rent => {:lease => :lease_rent_rolls}}, :charge_code]).where("lease_rent_rolls.id = #{lease_rr.id}
and rent_schedules.from_date < '#{Date.today.strftime("%Y-%m-%d %H:%M:%s")}'
and rent_schedules.to_date > '#{Date.today.strftime("%Y-%m-%d %H:%M%s")}'").group("charge_codes.charge_type")
获得此查询的结果。谢谢所有人!
答案 2 :(得分:0)
这样的事情:
@goods =Good.joins(:user).where("name like ?", "%#{@searched_good}%").where("category_id = ?", params[:category]).where("postal_code == ?", @searched_good_postal_code)
使用: - category_id和name属于Good数组 - postal_code属于User array