I have three tables, with a structure like this (they are in an MySQL DB) connected to my Laravel 5 API with Eloquent models:
# 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 |
At the moment I do a query like this:
$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 a result like this (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'm missing the title, description and color in the "parts" array which is included in the build set. So my question is, how to I add the title and the color to my response? Can I do that by using Eloquent models, or do I have to make my own DB query where I get all build sets and then iterate them and get all the parts and build set parts and then merge that result and add it to the build set.
Any one got a good solution which will give me items in the parts array formatted like this:
[
{
"title": "Part 1",
"color": "Red",
"amount": 25,
"special_info": ""
},
{
"title": "Part 2",
"color": "Green",
"amount": 75,
"special_info": ""
}
]