雄辩的集合方法,如only或except返回一个空集合

Pat*_*ros 13 collections laravel laravel-5.3

文档中,我使用该->only()方法测试了以下示例

$collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);

$filtered = $collection->only(['product_id', 'name']);

$filtered->all();

// ['product_id' => 1, 'name' => 'Desk']
Run Code Online (Sandbox Code Playgroud)

它确实有效.

但是,当我将该方法应用于我从数据库(Model)获取的集合时,

$myCollection = MyModel::orderBy('id','desc')->paginate(5);
$filtered=$myCollection->only(['id']);
        dd(filtered);
Run Code Online (Sandbox Code Playgroud)

返回的集合是空的!

Collection {#199 ?
  #items: []
}
Run Code Online (Sandbox Code Playgroud)

如果我dd($myCollection);从数据库中获取了集合,它确实充满了追加,属性等等.数据在表刀片视图中正确显示.

但是,如果我申请任一->only()->except()$myCollection方法...返回的集合是空的.

例如,这是集合的一部分,我只想显示id属性,例如,或者更多但不是全部:

LengthAwarePaginator {#218 ?
  #total: 3041
  #lastPage: 609
  #items: Collection {#219 ?
    #items: array:5 [?
      0 => MyModel {#220 ?
        #dates: array:1 [?]
        #appends: array:5 [?]
        #connection: null
        #table: null
        #primaryKey: "id"
        #keyType: "int"
        #perPage: 15
        +incrementing: true
        +timestamps: true
        #attributes: array:12 [?
          "id" => 3041
          "date" => "2017-01-25"
          "value1" => "12"
          "value2" => "20"
          "value3" => "22"
          "value4" => "25"
          "value5" => "46"
          "value6" => "48"
          "value7" => "50"
          "value8" => "$60,000,000.00"
          "created_at" => null
          "updated_at" => null
        ]
Run Code Online (Sandbox Code Playgroud)

但是当我申请时->only(['id']),该集合将返回空白.

我已经在没有分页的情况下测试了它,并且空集合的问题仍然是相同的,所以我认为它与它没有关系LengthAwarePaginator.

解决方法 不幸的是,我正在努力实现这一目标:

    $filtered = collect(['id'=>$myCollection->pluck(['id']),'Value1'=>$myCollection->pluck('value1')]);
dd($filtered);
Run Code Online (Sandbox Code Playgroud)

现在我得到了所需的集合,例如我只想要数据库中的两个属性或列:

Collection {#212 ?
  #items: array:2 [?
    "id" => Collection {#201 ?}
    "value1" => Collection {#211 ?}
  ]
}
Run Code Online (Sandbox Code Playgroud)

为什么会这样?我错过了什么?我该如何解决?

xmh*_*fiz 9

请注意,only()将返回具有指定键的项目,该应用于具有键或关联数组的数组.作为给出的示例,它是带有键的数组

['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]
Run Code Online (Sandbox Code Playgroud)

但是,如果您测试使用only()来自eloquent结果的集合,其中包含一个集合/对象数组(没有键).

[ object, object, object ]
Run Code Online (Sandbox Code Playgroud)

如果集合包含密钥,它将起作用.

[ 'product_id' => object, 'name' => object ]
Run Code Online (Sandbox Code Playgroud)

因此,在您的情况下只过滤指定键的值,我建议使用pluck()map()