Laravel Eloquent集合属性

时间:2016-12-14 10:39:40

标签: php laravel model attributes eloquent

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

我有一个扩展Eloquent Model的模型但是当我尝试用“where”输出我的数据库表时,例如

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

它返回一个包含许多对我来说无用的信息的集合,比如'guarded','keytype'......我的表的数据在'attributes'下。 按照laravel的指南,我看到每个人都像我一样使用,然后输出$mytable->myvalue,但这当然不适合我。

这里是我正在谈论的收藏的截图:

enter image description here

当我使用像"::where()"这样的东西时,我怎样才能始终获得属性?

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

1 个答案:

答案 0 :(得分:3)

如果你想获得几个属性做很多事情。可能第一种方式对你来说是最好的:

使用pluck()

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

使用select()

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

使用get()参数:

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

如果你想获得Eloquent集合,然后只使用属性构建一个数组,你可以使用toArray()

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

如果您想为新集合获取某些属性,请在集合中使用pluck()

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