ruby-on-rails - 使用 ruby on rails (>=6) ORM 的左外连接?
问题描述
有没有办法使用 rails ActiveRecord 简单地进行左外连接?
我在这里看到有一些使用原始 SQL 的方法,但我想使用“rails 方式”(假设有rails方式)
即检索由栗色区域表示的记录的查询:
为什么不使用原始 SQL(如这里) - 这是一个公平的问题。我的应用程序没有原始 sql,只有表单的语法,customer.purchases
所以我想保持整个应用程序的代码一致性。
解决方案
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
推荐阅读
- wpf - 无限循环中的可见性淡出和淡出
- arrays - 从 3 个向量创建 3d 矩阵
- php - 在主目录中创建日志的 Cron 作业
- php - mPDF TOC 未使用文档的 charset_in
- javascript - Google Apps 脚本 - “indexOf”方法的使用
- flutter - 无法使用gridview中的listview在页面上滚动
- linux - 如果用户未输入任何值,如何在我的 bash 脚本中显示错误
- flutter - 在颤动中格式化文本
- javascript - 选择器 materiel-ui 选项的部分视图
- nix - 具有自定义用户 systemd 单元的 Nixos 容器