首页 > 解决方案 > 将项目添加到 Laravel 中的每个对象

问题描述

当我得到 with A->all() 函数时,“A”模型有这样的列

results:[{
       id: 1
       Name: "Johsnson",
       product_id: "Q-123",
  }, {
       id: 2
       Name: "Thomas",
       product_id: "Q-345",
  }
  // etc

我得到了具有这样结构的“模型”

results: [{
       id:1
       product_id: "Q-123",
       product_name: "Apple",
  }, {
       id:2
       product_id: "Q-345",
       product_name: "Manggo",
  }

如何在 A 模型中返回包含所有项目的对象,并添加 product_name 和 product_id 键?

我试过了

$item= A::all();
foreach($item as $items){
  $name= B::select('product_name')->where('product_id',$items['product_id'])->get();
  $item->push($name);
}

但它不像我的意思那样工作

预期结果

results:[{
       id: 1
       Name: "Johsnson",
       product_id: "Q-123",
       product_name: "Apple", 
  }, {
       id: 2
       Name: "Thomas",
       product_id: "Q-345",
       product_name:"Manggo",
  }

标签: phplaravel

解决方案


您可以使用Eloquent 关系Collection::map()

class Product extends Model
{
    public function brand()
    {
        return $this->belongsTo(Brand::class);
    }
}
class Brand extends Model
{
    public function products()
    {
        return $this->hasMany(Brand::class, 'product_id');
    }
}

这是你如何使用它:

$item= Product::with('brand')->get()->map(function($product) {
    return (object)[
       'id' => $product->id,
       'Name' => $product->name,
       'product_id' => $product->product_id,
       'product_name' => $product->brand->product_name 
    ];
});

推荐阅读