【问题标题】:getting only one data from laravel collection seems difficult从 laravel 集合中只获取一个数据似乎很困难
【发布时间】:2017-08-24 07:00:53
【问题描述】:

我不明白,我有一些物品。 在这种情况下,该集合在索引 1 处仅包含一项,因为它是从更大的集合中过滤出来的。 关键是如何获得我需要的唯一数据,而不必重置索引的值然后在索引 0 处访问? 在这种情况下,我将始终在集合中只有一个项目,但索引可能不同,因此默认情况下我不能使用 [0] 索引。

//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?

}

我们没有直接访问数据的方法对我来说没有任何意义,或者如果我们有它我错过了它。 例如,我可以像这样在 $filtered 上使用 max() 或 min():

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

我知道在这种情况下找到最大id没有任何意义,但它表明我们可以在一个段落中找到数据。 我试过only('item_brand_id);,但是当数据在那里时返回空。

【问题讨论】:

  • 那么集合$item 的一件物品来自哪里?
  • 那是另一个集合,为了访问过滤后的数据有什么区别?

标签: php laravel collections


【解决方案1】:

你还有eloquent collection,所以你可以调用 first() 函数

$item_brand_id = $filtered->first()->item_brand_id;

【讨论】:

    【解决方案2】:

    filter() 在您想要一组匹配元素时使用,即使这只会产生一个元素。

    如果您知道只需要一个匹配真值测试的元素,请改用first()。它具有相同的签名。

    Item::where(...)->get()->first(function ($item) {
        return $item->item_color_id == 1;
    })->get('item_brand_id');
    

    【讨论】:

    • 不,因为我不想使用 2 个查询。在这种情况下,我需要过滤集合,因为该项目可能存在也可能不存在,如果存在,它总是只有一个,但另一个可以是多个。我只想使用一个查询来急切地加载所有内容。然后我也用其他方式过滤集合。
    【解决方案3】:

    您可以将数据库查询更改为只返回一个元素。如果结果总是只有一个,则无需加载整个集合。

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

    【讨论】:

    • 不,我不想要多个查询
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    相关资源
    最近更新 更多