Rails has_many:通过复杂的查询

时间:2018-05-27 10:22:56

标签: ruby-on-rails activerecord

我有这三个模型与has_many:通过关系:

class Package < ApplicationRecord
  belongs_to :user
  belongs_to :shipment
end

class User < ApplicationRecord
  has_many :packages
  has_many :shipments, through: :packages
end

class Shipment < ApplicationRecord
  has_many :packages
  has_many :users, through: :packages
end

鉴于发货@shipment,我希望获得该货件的所有用户,按user_id分组,然后为每个用户获取他们在此特定@shipment中获得的包裹。 使用:

@shipment.users.each do |user|
  user.packages
end

获取所有用户软件包的列表 ,但我只需要获取@shipment 中的软件包。 我该如何查询?

2 个答案:

答案 0 :(得分:0)

如果您希望保持与目前相同的格式。尝试类似:

@shipment.users.group(:email).each do |user|
  user.packages(where: @shipment)
end

答案 1 :(得分:0)

看起来您可以从@shipment.packages开始,然后将其按user_id分组,如下所示:

@shipment.packages.group_by(:user_id)

因此,您将获得由user_id索引的哈希值,其中值是具有给定user_id的货件包列表。

E.g。假设您有以下包裹:

+----------------------------+
| id | user_id | shipment_id |
|  1 |       1 |           1 |
|  2 |       1 |           2 |
|  3 |       2 |           3 |
|  4 |       2 |           1 |
|  5 |       3 |           1 |
|  6 |       2 |           1 |
+----------------------------+

然后你会得到这样的东西:

@shipment = Shipment.find(1)
@shipment.packages.group_by(&:user_id) #=> {1 => [<Package id=1>], 2 => [<Package id=4>, <Package id=6>], 3 => [<Package id=5>]}
相关问题