sql - 我想通过以下方式获得`has_many的不同记录:`关联
问题描述
我有一个关联的数据库,如下所示:
class Subscription < ActiveRecord::Base
belongs_to :plan
has_one :role, through: :plan
end
class Plan < ActiveRecord::Base
has_many :subscriptions
belongs_to :role
end
class Role < ActiveRecord::Base
has_one :plan
end
我想要所有有roles.name = 'Gold'
但只有不同的订阅role_id
在我执行了这个查询之后:
Subscription.includes(:plan => [:role]).where("roles.name = 'Gold'")
我得到的结果如下:
| subscription_id | plan_id | role_id |
| 1 | 1 | 3 |
| 2 | 1 | 3 |
| 3 | 1 | 3 |
| 4 | 2 | 4 |
| 5 | 2 | 4 |
| 6 | 3 | 5 |
role_id
我想要的结果是(由or区分plan_id
,任何一个都可以工作,因为has_one
它们之间存在关联)。我尝试运行以下查询,但它选择 distinct onsubscription.id
从而给出相同的结果:
Subscription.includes(:plan => [:role]).where("roles.name = 'Gold'").distinct("role_id")
我想要的结果:
| subscription_id | plan_id | role_id |
| 1 | 1 | 3 |
| 4 | 2 | 4 |
| 6 | 3 | 5 |
有没有办法通过 activerecord 来实现这一点,还是我必须运行一个each
循环才能role_id
在收到的结果上获得不同的值?
解决方案
推荐阅读
- javascript - 如何使用 javascript 在动态数据列表中应用 css 样式?
- c - HTTP 服务器应该如何将请求参数传递给脚本?
- vue.js - 为什么我不能使用 vue-konva 为太多或更多形状创建一层?
- python - 模板渲染期间出错:“ManyToOneRel”对象没有属性“attname”
- html - 如何在导航栏中使 div 居中(不带空格)
- oauth-2.0 - 移至 v2.0 权限后,同意提示不会询问在 AD App 中设置的所有权限
- css - 你如何防止相对容器内绝对定位的孩子溢出?
- angular - Angular 7 中的手风琴组件
- canvas - 如何从不同的 ObservableCollection 集合绑定到 ContentTemplate 中的每个画布?
- apache - .htaccess 如何隐藏 php 扩展名