首页 > 解决方案 > 使用 ruby​​ on rails (>=6) ORM 的左外连接?

问题描述

有没有办法使用 rails ActiveRecord 简单地进行左外连接?

在这里看到有一些使用原始 SQL 的方法,但我想使用“rails 方式”(假设有rails方式)

即检索由栗色区域表示的记录的查询:

在此处输入图像描述

为什么不使用原始 SQL(如这里) - 这是一个公平的问题。我的应用程序没有原始 sql,只有表单的语法,customer.purchases所以我想保持整个应用程序的代码一致性。

标签: ruby-on-railsactiverecordrails-activerecordruby-on-rails-6

解决方案


Rails >= 5 appears to have this capability built in.

Here's a 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):

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


推荐阅读