Skip to content
Advertisement

Adding additional column to the result of relationship in eloquent

I have two models. Both of them are pivots because they join other tables. But also they have a relationship with themselves.

JavaScript

I want to get all entities of CompanyUserProduct but with the additional column user_id from CompanyUser, so I can do pluck('user_id') on the collection and get all IDs at once. Is it possible to do it in Eloquent, or must I use Query Builder?

JavaScript

Advertisement

Answer

You can do

JavaScript

To retrieve the CompanyUserProduct along with the id and user_id of compantUser.

Note: whatever your primary key for companyUser – make sure you select it as well. (In this case assumed to be id)

Once you retrieve the collection, the user_id will be under companyUser for each CompanyUserProduct

So, you can pluck it using dot notation.

eg:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement