我们需要在rails应用中检索logs
的{{1}}。简体中文的条件是customer_comm_record的日志基于:
customer comm record
#1的SQL代码可以是(#1. the sales_id in customer comm record's customers is equal to current user id
#2. the sales_id in customer comm record's customer's project is equal to the current user id.
):
SQL#1
#2的SQL代码可以是(Log.joins(:customer_comm_record =>:customer).where('customers.sales_id = ?', session[:user_id])
):
SQL#2
以下是我们在一行中提出的问题(Log.joins(:customer_comm_record =>{ :customer => :projects}).where('projects.sales_id = ?', session[:user_id])
):
SQL#3
上面Log.joins(:customer_comm_record =>{ :customer => :projects}).where('customers.sales_id = ? OR projects.sales_id = ?', session[:user_id], session[:user_id])
返回的SQL代码是(将session [:user_id]替换为1):
rails console
问题是天气 SELECT "logs".* FROM "logs" INNER JOIN "customer_comm_records" ON "customer_comm_records"."id" = "logs"."customer_comm_record_id" INNER JOIN "customers" ON "customers"."id" = "customer_comm_records"."customer_id" INNER JOIN "projects" ON "projects"."customer_id" = "customers"."id" WHERE (customers.sales_id = 1 OR projects.sales_id = 1)
。有人可以回答这个问题吗?如果不是,那么什么是正确的?感谢。
答案 0 :(得分:2)
唯一的区别是:
projects.customer_id
)。最后的区别仅在客户不一定有任何项目时才有意义。否则,第二种方法更好,因为它避免了处理重复。
如果客户并不总是有项目,那么一个简单的解决方法就是使用includes
代替joins
:
Log.includes(:customer_comm_record =>{ :customer => :projects}).
where('customers.sales_id = :id OR projects.sales_id = :id', id: session[:user_id])
这将强制LEFT JOIN并将返回客户,无论他们是否与项目相关联。