简体   繁体   English

如何在Ruby Join查询中编写此SQL查询(Ruby on Rails)

[英]How to write this sql query in Ruby Join query (Ruby on Rails)

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

I am using this SQL Query in model using find_by_sql , But i should get this same result in Ruby Joins where condition in model without the help of SQL. 我在使用find_by_sql模型中使用此SQL查询,但是我应该在没有SQL帮助的情况下在Ruby Joins中获得相同的结果。

If you will provide association then it will be more helpful to provide solution. 如果您将提供关联,那么提供解决方案将更有用。

Now, I am considering : 现在,我正在考虑:

LeaseRentRoll has one or many leases. LeaseRentRoll有一个或多个租约。

Lease have many rents. 租赁有很多租金。

Rent have many rent_schedules. 租金有很多租金时间表。

and RentSchedule have many charge_codes. 和RentSchedule有许多charge_code。

If LeaseRentRoll has one lease: 如果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") rent_schedules.from_date,rent_schedules.to_date,charge_codes.charge_type as cc“)

If LeaseRentRoll have many leases: 如果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")

Please have a look on attached image. 请看附件图片。 It will help to understand more to above query. 这将有助于对上述查询有更多的了解。

在此处输入图片说明

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")

Got the Result for this Query.Thanks Everyone! 得到了该查询的结果。谢谢大家!

Something like this: 像这样:

@goods =Good.joins(:user).where("name like ?", "%#{@searched_good}%").where("category_id = ?", params[:category]).where("postal_code == ?", @searched_good_postal_code)

with: - category_id and name belong to Good array - postal_code belongs to User array 其中:-category_id和name属于Good数组-postal_code属于User数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM