我有 User
、Assignment
和 Account
模型。用户可以属于多个帐户,并且帐户有多个分配。作为帐户的管理员,您可以将用户“分配”到任务中。我正在尝试查找分配给特定任务的用户数。此外,用户和任务有一个名为 assignment_relationships
的连接表。该表有一个 bool 值,如果用户被分配到该表,该值就会翻转——该属性称为 designated
。这有点令人困惑,但应该非常简单。以下是协会:
用户:
class User < ApplicationRecord
has_many :account_memberships
has_many :accounts, through: :account_memberships
has_many :assignment_relationships
has_many :assignments, through: :assignment_relationships
end
账号:
class Account < ApplicationRecord
has_many :assignments
end
作业:
class Assignment < ApplicationRecord
belongs_to :account
has_many :assignment_relationships
has_many :users, through: :assignment_relationships
end
分配关系:
class AssignmentRelationship < ApplicationRecord
belongs_to :user
belongs_to :assignment
end
作为回顾,我试图找到一个查询来告诉我有多少用户被分配到一个特定的任务。感谢您的帮助!
最佳答案
我觉得也许我在你的问题中遗漏了一些东西(因为我的回答非常简单)但你为什么不能这样做:
@assignment.users.count
因为看起来你的 has_many, through:
关系设置正确,在 Assignment
对象上调用 users
应该正确通过您的 assignment_relationships
联接表以返回与作业相关的所有用户。
关于mysql - 如何通过连接表查找基于关联的记录数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42171698/