【发布时间】:2015-06-16 05:20:05
【问题描述】:
我有三个表,具有这样的结构(它们在 MySQL 数据库中)连接到我的 Laravel 5 API 和 Eloquent 模型:
# build_sets table
| id | title | description |
# parts table
| id | title | description | color |
# build_set_parts table
| id | build_set_id | part_id | amount | special_info |
目前我做这样的查询:
$buildSets = array();
foreach(BuildSet::with('parts')->get() as $buildSet) {
$temp = json_decode($buildSet);
$temp->parts = $buildSet->parts;
$buildSets[] = $temp;
}
return $buildSets;
我的模型看起来像这样:
class BuildSet extends Model
{
protected $table = 'build_sets';
protected $hidden = ['created_at', 'updated_at'];
public function parts()
{
return $this->hasMany('App\Models\BuildSetPart');
}
}
class Part extends Model
{
protected $table = 'parts';
protected $hidden = ['id', 'created_at', 'updated_at'];
public function buildSets()
{
return $this->hasMany('App\Models\BuildSet');
}
}
class BuildSetPart extends Model
{
protected $table = 'build_set_parts';
protected $hidden = ['id', 'build_set_id', 'part_id', 'created_at', 'updated_at'];
public function buildSet()
{
return $this->belongsTo('App\Models\BuildSet');
}
public function part()
{
return $this->belongsTo('App\Models\Part');
}
}
我得到这样的结果(JSON 响应):
[
{
"id": 1,
"title": "Build set 1",
"description": "This is a small build set.",
"parts": [
{
"amount": 150,
"special_info": ""
},
{
"amount": 400,
"special_info": "Extra strong"
},
{
"amount": 25,
"special_info": ""
}
]
},
{
"id": 2,
"title": "Build set 2",
"description": "This is a medium build set.",
"parts": [
{
"amount": 150,
"special_info": ""
},
{
"amount": 400,
"special_info": "Extra strong"
},
{
"amount": 25,
"special_info": ""
},
{
"amount": 25,
"special_info": ""
},
{
"amount": 25,
"special_info": ""
}
]
}
]
如您所见,构建集中包含的“部件”数组中缺少标题、描述和颜色。 所以我的问题是,如何在我的回复中添加标题和颜色?我可以通过使用 Eloquent 模型来做到这一点,还是我必须进行自己的数据库查询,在其中获取所有构建集,然后迭代它们并获取所有部件并构建集部件,然后合并该结果并将其添加到构建集.
任何人都有一个很好的解决方案,它将给我部件数组中的项目,格式如下:
[
{
"title": "Part 1",
"color": "Red",
"amount": 25,
"special_info": ""
},
{
"title": "Part 2",
"color": "Green",
"amount": 75,
"special_info": ""
}
]
【问题讨论】:
标签: php mysql laravel eloquent laravel-5