【问题标题】:Laravel Collection with Where(), Min() & pluck() ProblemLaravel Collection with Where(), Min() & pluck() 问题
【发布时间】:2020-09-23 12:35:25
【问题描述】:

我正在努力从一系列项目中获取特定日期。我想要 minimum['lastUsed'] 项目的 'id'。

例子

$getIdOfLastUsedItem = collect(//arrayOfItems)
            ->where('working', true) // works great & filters working items
            ->min('lastUsed') // returns 2
            ->pluck('id'); // Error


// arrayOfItems looks like this
array:11 [
  0 => array:3 [
    "id" => 6
    "working" => true
    "lastUsed" => 2
  ]
  1 => array:3 [
    "id" => 7
    "working" => false
    "lastUsed" => 1
  ]
  2 => array:3 [
    "id" => 8
    "working" => true
    "lastUsed" => 5
  ]...

我对 $getIdOfLastUsedItem 的目标将返回 'id' => 6 或只是 6

【问题讨论】:

  • pluck('id') 只需将 pluck 更改为 select('id') 它会给你你想要的
  • @ShahrukhKhan 是一个集合,而不是一个查询构建器,min 返回一个整数,因此不能调用任何方法,因为它不是对象
  • @ShahrukhKhan 不起作用

标签: php laravel collections laravel-7 collect


【解决方案1】:

已修复。

$getIdOfLastUsedItem = collect($array)
                ->where('working', true)
                ->sortBy('lastUsed')
                ->pluck('id')
                ->first()
        ;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-05
    • 2017-11-29
    • 2017-01-12
    • 2019-05-10
    • 1970-01-01
    • 2020-07-09
    • 2021-06-28
    • 1970-01-01
    相关资源
    最近更新 更多