I have three tables with a structure like this (they are in the MySQL database) connected to my Laravel 5 API with Eloquent:
| id | title | description |
| id | title | description | color |
# build_set_parts table
| id | build_set_id | part_id | amount | special_info |
I am currently making this request:
$buildSets = array();
foreach(BuildSet::with('parts')->get() as $buildSet) {
$temp = json_decode($buildSet);
$temp->parts = $buildSet->parts;
$buildSets[] = $temp;
}
return $buildSets;
And my models look like this:
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');
}
}
I get this result (JSON response):
[
{
"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": ""
}
]
}
]
As you can see, I am missing the name, description and color in the "parts" array, which is included in the assembly set. So my question is: how do I add a title and color to my answer? Can I do this using Eloquent models, or do I need to make my own database query when I get all the assembly sets and then iterate over them and get all the parts and create many parts, and then combine this result and add it to the assembly set .
, , :
[
{
"title": "Part 1",
"color": "Red",
"amount": 25,
"special_info": ""
},
{
"title": "Part 2",
"color": "Green",
"amount": 75,
"special_info": ""
}
]