如何从Laravel集合中仅获取特定属性?
如何从Laravel 8中的集合中获取所有特定ID 我正试图通过foreach循环从集合中获取如何从Laravel集合中仅获取特定属性?,laravel,collections,eloquent,Laravel,Collections,Eloquent,如何从Laravel 8中的集合中获取所有特定ID 我正试图通过foreach循环从集合中获取食物项目id。但我只得到第一个项目ID。我不仅要第一个项目,还要所有项目ID 我想在这里获取所有食品项目id表单 Illuminate\Database\Eloquent\Collection {#1083 ▼ #items: array:2 [▼ 0 => App\Models\Cart {#1082 ▼ #guarded: [] #connection:
食物项目id
。但我只得到第一个项目ID。我不仅要第一个项目,还要所有项目ID
我想在这里获取所有食品项目id
表单
Illuminate\Database\Eloquent\Collection {#1083 ▼
#items: array:2 [▼
0 => App\Models\Cart {#1082 ▼
#guarded: []
#connection: "mysql"
#table: "carts"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:8 [▼
"id" => 265
"food_item_id" => 6
"user_id" => 3
"quantity" => 3
"price" => 124
"total_price" => 372
"created_at" => "2021-01-28 08:22:16"
"updated_at" => "2021-01-28 08:51:51"
]
#original: array:8 [▶]
#changes: []
#casts: []
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
}
1 => App\Models\Cart {#1291 ▼
#guarded: []
#connection: "mysql"
#table: "carts"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:8 [▼
"id" => 267
"food_item_id" => 4
"user_id" => 3
"quantity" => 1
"price" => 179
"total_price" => 179
"created_at" => "2021-01-28 08:51:54"
"updated_at" => "2021-01-28 08:51:54"
]
#original: array:8 [▶]
#changes: []
#casts: []
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
}
]
}
是我干的
$food_item_ids = $food_item_id->pluck('food_item_id')->all();
我得到了一个ID数组,现在我想找到这个
$food_item = FoodItemPrice::where('food_item_id', $food_item_ids)->get();
我想找到与食物项目ID匹配的FoodItemPrice ID。您正在使用的是Laravel提供的一些非常方便的。你特别想要的是
更新
假设上面的$food\u item\u id
有一组id
,并且您希望使用这些$food\u items
来查找您的$food\u items
,那么您可以执行以下操作:
$food_items = FoodItemPrice::whereIn('food_item_id', $food_item_ids)->all());
要获取集合的特定字段/属性的所有值的所有数组,可以使用
pluck()
所以你可以这样做:
$items=Cart::all();
$foodItemIds=$items->pull('food\u item\u id');
发布您尝试过的代码?请发布预期结果。我更新了帖子。请再核对一下,谢谢。我已经为您更新了我的答案。信息性答案。它显示了对未定义方法illumb\Database\elount\Builder::all()的错误调用是
foodemprice
一个有说服力的模型吗?
$food_items = FoodItemPrice::whereIn('food_item_id', $food_item_ids)->all());