问题
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