Laravel Eloquent collection attributes

妖精的绣舞 提交于 2019-12-24 07:06:26

问题


I'm developing a webapp with Laravel 5.2 but there is an issue that I can't solve.

I have a model which extends Eloquent Model but when I try to output my database table with "where", for example

\App\MyModel::where('id_table', 23)->first();

It return a collection with many informations not useful for me at this moment like 'guarded', 'keytype'... and my table's data are under 'attributes'. Following laravel's guide I see everybody use simply where like me and then output with $mytable->myvalue, but this cannot work for me of course.

Here a screenshot with the collection I'm talking about:

How can I get always just attributes when I use something like "::where()"?

I've tried getAttributes() but it gives me a 500 error.


回答1:


If you want to get just couple of attributes do many things. Probably first way will be the best for you:

Use pluck():

\App\MyModel::where('id_table', 23)->pluck('id', 'name');

Use select():

\App\MyModel::select('id', 'name')->where('id_table', 23)->get();

Use get() with parameters:

\App\MyModel::where('id_table', 23)->get(['id', 'name']);

If you want to get Eloquent collection and only then build an array with just attributes, you can use toArray():

\App\MyModel::where('id_table', 23)->get()->toArray();

If you want to get some attributes to a new collection, use pluck() on collection:

$collection = \App\MyModel::where('id_table', 23)->get();
$names = $collection->pluck('name');


来源:https://stackoverflow.com/questions/41140512/laravel-eloquent-collection-attributes

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