从文档中,我已经使用->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']
并且它确实起作用了。
然而,当我将这种方法应用于我从数据库中获取的集合(模型)时,
$myCollection = MyModel::orderBy('id','desc')->paginate(5);
$filtered=$myCollection->only(['id']);
dd(filtered);
返回的集合为空!
Collection {#199 ▼
#items: []
}
如果我从数据库获取collection,然后使用
dd($myCollection);
方法,它确实充满了appends,attributes等内容。这些数据在表格blade视图中显示正确。但是如果我将
->only()
或->except()
方法应用于$myCollection
,返回的collection会为空。例如,这是collection的一部分,我只想显示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
]
当我应用->only(['id'])
时,集合返回为空。
我已经测试了没有分页,空集合的问题仍然存在,所以我不认为它与LengthAwarePaginator
有关。
解决方法不幸的是,我正在以艰难的方式实现这一点:
$filtered = collect(['id'=>$myCollection->pluck(['id']),'Value1'=>$myCollection->pluck('value1')]);
dd($filtered);
现在我已经得到了所需的集合,例如我只想从数据库中获取两个属性或列:
Collection {#212 ▼
#items: array:2 [▼
"id" => Collection {#201 ▶}
"value1" => Collection {#211 ▶}
]
}
为什么会发生这种情况?我漏掉了什么?该如何解决?
$myCollection
返回的内容吗? - PaladiNcollect()
和pluck()
方法,现在它按预期工作了。 - Pathros