【发布时间】:2021-05-02 04:23:14
【问题描述】:
如何从 Laravel 8 的集合中获取所有特定 ID??
我正在尝试通过 foreach 循环从集合中获取 food_item_id。但我只得到第一个项目 ID。我不仅想要第一个项目,还想要所有项目 ID。
我想在这里获取所有food_item_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();
我想找到与 food_item_ids 匹配的 FoodItemPrice ID。
【问题讨论】:
-
发布您尝试过的代码?
-
请发布预期结果。
标签: laravel collections eloquent