gpt4 book ai didi

laravel - Eloquent 集合方法,例如 only 或 except 返回一个空集合

转载 作者:行者123 更新时间:2023-12-03 22:32:29 27 4
gpt4 key购买 nike

来自 docs ,我已经用 ->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: []
}

如果我 dd($myCollection);从数据库中得到的集合,确实充满了追加、属性等东西。数据正确显示在表格 Blade View 中。

但如果我申请 ->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
]

但是当我申请 ->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 ▶}
]
}

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

最佳答案

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

['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]

但是,如果您测试使用 only()从 eloquent 结果中收集,其中包含一个集合/对象数组(没有键)。
[ object, object, object ]

如果集合包含键,它将起作用。
[ 'product_id' => object, 'name' => object ]

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

关于laravel - Eloquent 集合方法,例如 only 或 except 返回一个空集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41971901/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com