首页 > 解决方案 > 如何从 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。

标签: laravelcollectionseloquent

解决方案


你正在使用collectionLaravel 提供了一些非常方便的辅助方法。您特别关注的将是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());

推荐阅读