简体   繁体   English

在轨道上使用 ruby 左外连接 (>=6) ORM?

[英]Left outer join using ruby on rails (>=6) ORM?

Is there a way to simply do a left outer join using rails ActiveRecord?有没有办法使用导轨 ActiveRecord 简单地进行左外连接?

I see here there are some ways using raw SQL, but I'd like to use the 'rails way' (presuming there is a rails way)在这里看到有一些使用原始 SQL 的方法,但我想使用“导轨方式”(假设导轨方式)

ie a query to retrieve the records represented by the maroon area:即检索由栗色区域表示的记录的查询:

在此处输入图像描述

Why not use raw SQL (like here ) - that's a fair question.为什么不使用原始 SQL (像这里) - 这是一个公平的问题。 My app has no raw sql, only syntax of the form customer.purchases so I'd like to keep the code consistence across the app.我的应用程序没有原始 sql,只有customer.purchases形式的语法,所以我想保持整个应用程序的代码一致性。

Rails >= 5 appears to have this capability built in. Rails >= 5 似乎内置了此功能。

Here 'sa simple example: 是一个简单的例子:

User.left_outer_joins(:posts)
=> SELECT "users".* FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" = "users"."id"

Here 's another example: 是另一个例子:

Author.left_joins :posts, :comments

# Produces:
Author Load (0.1ms)  SELECT "authors".* FROM "authors" LEFT OUTER JOIN "posts" ON "posts"."author_id" = "authors"."id" LEFT OUTER JOIN "comments" ON "comments"."author_id" = "authors"."id"

This example from RailsGuides is also handy to know (although it contains some raw SQL):这个来自 RailsGuides 的例子也很容易知道(尽管它包含一些原始 SQL):

Customer.left_outer_joins(:reviews).distinct.select('customers.*, COUNT(reviews.*) AS reviews_count').group('customers.id')

#Produces:
SELECT DISTINCT customers.*, COUNT(reviews.*) AS reviews_count FROM customers
LEFT OUTER JOIN reviews ON reviews.customer_id = customers.id GROUP BY customers.id

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

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