如何从Laravel Collection中仅获得特定属性



如何从Laravel 8中的集合中获取所有特定ID??

我正试图通过foreach循环从集合中获取food_item_id。但我只得到第一个项目ID。我不仅想要第一个项目,还想要所有项目ID。

我想在这里拿到所有的food_item_id表格。

IlluminateDatabaseEloquentCollection {#1083 ▼
#items: array:2 [▼
0 => AppModelsCart {#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 => AppModelsCart {#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();

我想找到与food_item_ids匹配的FoodItemPrice ID。

您正在使用一个collection,Laravel为它提供了一些非常方便的助手方法。你特别想要的是pluck

$food_item_ids = $collection->pluck('food_item_id')->all();

更新

假设上面的$food_item_ids有一个ids的集合,并且您想使用它们来使用这些ids找到您的$food_items,那么您可以执行:

$food_items = FoodItemPrice::whereIn('food_item_id', $food_item_ids)->all());

要获取集合的特定字段/属性的所有值的所有数组,可以使用pluck()

所以你可以做一些类似的事情:

$items = Cart::all();
$foodItemIds = $items->pluck('food_item_id');

https://laravel.com/docs/8.x/collections#method-拔出

最新更新