Laravel雄辩收藏属性 [英] Laravel Eloquent collection attributes

查看:121
本文介绍了Laravel雄辩收藏属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Laravel 5.2开发一个webapp,但是有一个我无法解决的问题。



我有一个扩展Enloquent模型的模型,但是当我尝试使用where输出我的数据库表,例如

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

它返回一个包含许多信息的集合,在这个时候对我来说没有用,就像'guarded','keytype '...我的表的数据属于'属性'。
跟随laravel的指南,我看到每个人都像我一样使用,然后输出与 $ mytable-> myvalue ,但这对我来说当然不行。 p>

这里是我正在谈论的集合的截图:





当我使用类似:: where()时,我该如何才能得到属性?



我尝试过 getAttributes(),但它给我一个500错误。

解决方案

如果你想获得几个属性,做许多事情。可能第一种方式对你最好:



使用 pluck()

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

使用 select()

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

使用 get() / p>

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

如果要获得Eloquent集合,只能使用属性构建数组,则可以使用< a href =https://laravel.com/docs/5.3/collections#method-toarray =nofollow noreferrer> toArray()

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

如果您想要获取一些新集合的属性,请使用 pluck() 收藏:

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


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.

解决方案

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

这篇关于Laravel雄辩收藏属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆