laravel - 如何从 Laravel 集合中仅获取特定属性?
问题描述
如何从 Laravel 8 的集合中获取所有特定 ID?
我正在尝试food_item_id
通过 foreach 循环从集合中获取。但我只得到第一个项目 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。
解决方案
你正在使用collection
Laravel 提供了一些非常方便的辅助方法。您特别关注的将是pluck
.
$food_item_ids = $collection->pluck('food_item_id')->all();
更新
假设$food_item_ids
在上面有一个集合ids
并且你想用它们来找到你$food_items
使用的那些ids
,那么你可以这样做:
$food_items = FoodItemPrice::whereIn('food_item_id', $food_item_ids)->all());
推荐阅读
- swift - 使用 UIVIewPropertyAnimator 摇动视图
- postgresql - COPY 和 pg_dump —data-only 有什么区别
- regex - VSCode 片段中用于删除文件扩展名的正则表达式语句
- swift - 在 localizable.strings 文件中添加超链接文本
- pytorch - 如何使用来自第一个网络的预测图作为第二个网络的上下文(自动上下文)
- android - Android:即使没有任何更改,资源链接在测试执行时也会失败
- spring - java - 如何使用批处理将excel数据插入数据库?
- python - 在现有工作簿中多次将唯一数据框写入同一张工作表
- string - 如何使用AWK将包含特定字符串的行之后的行的第三列中的值打印到不同的文件?
- sql - 如何以最佳方式锁定postgres中的数据