Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include column for has_many through

I got three models, User, Team and Membership. In the Membership model a got a field, role, that stores the user role for the current team.

When a team got a lot of users and I list them and also show the user role for the team my query count explode of course.

Is there a way to load all the Team users and include the role column from the Membership model?

User
has_many :memberships, dependent: :destroy
has_many :teams,       through: :memberships 

Team
has_many :memberships, dependent: :destroy
has_many :users,       through:   :memberships

Membership
belongs_to :user
belongs_to :team
like image 877
sandelius Avatar asked May 03 '26 00:05

sandelius


1 Answers

I belive this will work

team = Team.first #for example
users = team.users.select("*, memberships.role AS role")

so each user will get role

users.first.role
like image 56
Aleks Avatar answered May 04 '26 12:05

Aleks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!