Reputation: 2105
I want to get all users that is related to a certain conversation. The pivot table has user_id
and conversation_id
columns. user_id
and conversation_id
references the id
column on user and conversations table respectively.
So I did :
Conversations::find($conv_id)->users()
This is ok but it returns all the details of the related user. Based on the code above, how do I return only certain columns of the user such as id
and name
?
P.s. Additionally, I know I can do this by creating a modal for pivot table but it seems like an overkill. Is it a good practice to create a modal for pivot table?
I have tried
Conversations::select('id','name')->find($conv_id)->users()->get()->toArray();
but the result is still the same.
I have also tried
Conversations::find($conv_id)->users()->get(array('id','name'))->toArray();
but it gives the error :
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in field list is ambiguous..
Thank you for your time.
Upvotes: 3
Views: 2788
Reputation: 10533
As you are selecting data from two tables that both contain a field called id
, hence why you receive the Column 'id' in field list is ambiguous...
error.
If you try the same query again but define which id
you wish to select using dot notation in the form table.field
it should work.
Conversations::find($conv_id)->users()->get(array('users.id','name'))->toArray();
Upvotes: 5