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

家住魔仙堡 提交于 2019-12-12 12:31:14

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/24689563/laravel-4-how-to-get-selected-specific-columns-in-a-many-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!