dongpa5277 2017-03-30 11:19
浏览 361
已采纳

从laravel集合中只获取一个数据似乎很难

I don't get this, I have a collection of items. The collection contains in this case one and only one item at index 1 as it was filtered from a bigger collection. The point is how do I get the only piece of data I need without having to reset the values of the index and then accessing at index 0 ?? This is a case where I will always have only ONE item in the collection but the index at could be different so I can't use the [0] index by default.

//returns all items with 'item_color_id" = 1

$item = Item::where(//some constraints);

$filtered = $item->filter(function ($i) {
                return $i->item_color_id == 1;
            });

if (count($filtered)) {

    //need to access a single data inside the collection
    // like for example 'item_brand_id'
    //I can do it like this:

    $filtered = $filtered->values();

    $item_brand_id = $filtered[0]['item_brand_id'];

    //but what sense does it have?? how can we access 'item_brand_id'
    //from $filtered without resetting the indexes?

}

it doesn't make any sense to me that we don't have a method to access the data directly, or if we have it I missed it. For example I coould use max() or min() on $filtered like this:

$max_brand_id = $filtered->max('item_brand_id');

It doesn't make any sense to find the max id in this case I know, but it shows that we can find the data in one passage. I tried only('item_brand_id); but that returns empty while the data is there.

  • 写回答

3条回答 默认 最新

  • dsbckxk165039 2017-03-30 13:43
    关注

    You still have eloquent collection so you can do just call first() function

    $item_brand_id = $filtered->first()->item_brand_id;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助