简体   繁体   中英

Laravel 4 : How to get selected/specific columns in a many to many relationship?

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 ?

Ps 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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM