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

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

相关推荐 更多相似问题