doulu4534 2016-12-14 10:39
浏览 212
已采纳

Laravel Eloquent集合属性

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:

enter image description here

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条回答 默认 最新

  • dongle7637 2016-12-14 10:42
    关注

    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');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度