php - 将项目添加到 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",
}
解决方案
您可以使用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
];
});
推荐阅读
- sparql - 如何“旋转” SPARQL 导致“循环”?
- simulation - Anylogic变量未更新
- css - jQuery UI 可排序:防止在全高列之间使用连接列表进行水平滚动
- python - 根据另一个列表中的属性对对象列表进行排序
- c# - 如何创建包含两个 DateTime 对象之间的日期的字符串数组或列表?
- android - 为什么 Android 上的阴影会被其他组件覆盖?
- r - 简单数学的并行性
- python - 如何修复“缺少 google-api-python-client”?使用 Python、Jupyter Notebook 和 SpeechRecognition
- openshift - 为 Openshift 3.10 S2I Maven 构建配置 settings.xml
- reactjs - 为什么我无法在我的 react 应用程序中通过 CDN 使用包?