我有三个表,结构如下(它们在 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": ""
}
]
最佳答案
从您的模型中,您得到了 BuildSet
和 Part
之间的多对多关系。
因此,在BuildSet
中,可以使用hasManyThrough
关系。
模型 BuildSet
public function parts()
{
return $this->hasManyThrough('App\Models\Part', 'App\Models\BuildSetPart');
}
来源:http://laravel.com/docs/5.0/eloquent#relationships
无论如何,如果你想保持BuildSet
和BuildSetPart
之间的关系。
我建议您改用它。
public function buildSetPart()
{
return $this->hasMany('App\Models\BuildSetPart');
}
注意:现在,BuildSet
模型parts()
和buildSetPart()
都得到了
创建关系后,您可以替换代码
$buildSets = array();
foreach(BuildSet::with('parts')->get() as $buildSet) {
$temp = json_decode($buildSet);
$temp->parts = $buildSet->parts;
$buildSets[] = $temp;
}
return $buildSets;
与
return BuildSet::with('parts')->get();
或者,如果您想要 JSON 格式的输出
return BuildSet::with('parts')->toJson();
关于php - 如何在 Laravel 5 中加入模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29562274/