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

从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;
    
    打赏 评论
  • doupi6737 2017-03-30 11:37

    filter() is used when you want a collection of matching elements, even if that only results in one element.

    If you know that you only want one element that matches a truth test, use first() instead. It has the same signature.

    Item::where(...)->get()->first(function ($item) {
        return $item->item_color_id == 1;
    })->get('item_brand_id');
    
    打赏 评论
  • doume5227 2017-03-30 11:37

    You could change your database query to just return one element. If the result is always just one, there is no need to load an entire collection.

    $item = Item::where(/*some constraints*/)->where('item_color_id', 1)->first();
    if (isset($item))
        echo $item->item_brand_id;
    
    打赏 评论

相关推荐 更多相似问题