我认为,我想要完成的是基于相关模型的笛卡尔结果。我希望通过热切的加载来做到这一点。
我雄辩的查询如下:
$results = PartBasePart::whereIn('id', array(1,2,3,4,5))
->with('materials')
->with('profiles')
->get();
正在产生以下结果:
+Collection
PartBasePart - Model
+Collection
Material - Model1
Material - Model2
Material - Model3
Material - Model4
Material - Model5
+Collection
Profile - Model1
欲望是:
+Collection
PartBasePart - Model
+Collection
Material - Model1
+Collection
Profile - Model1
Material - Model2
+Collection
Profile - Model1
Material - Model3
+Collection
Profile - Model1
Material - Model4
+Collection
Profile - Model1
Material - Model5
+Collection
Profile - Model1
这怎么可能?我可以在每个Material集合中获得'Profile - Model1'的实例吗?
模型定义如下:
class PartBasePart extends Eloquent
{
public function materials()
{
return $this->belongsToMany(\App\Models\Material::class)
->withPivot('id');
}
public function profiles()
{
return $this->belongsToMany(\App\Models\Profile::class)
->withPivot('id');
}
}
class Material extends Eloquent
{
public function partBaseParts()
{
return $this->belongsToMany(\App\Models\PartBasePart::class)
->withPivot('id');
}
public function profiles()
{
return $this->belongsToMany(\App\Models\Profile::class)
->withPivot('id');
}
}
class Profile extends Eloquent
{
public function materials()
{
return $this->belongsToMany(\App\Models\Material::class)
->withPivot('id');
}
public function partBaseParts()
{
return $this->belongsToMany(\App\Models\PartBasePart::class)
->withPivot('id');
}
}
答案 0 :(得分:0)
这应该这样做:
$results = PartBasePart::whereIn('id', array(1,2,3,4,5))
->with('materials.profiles')
->get();
您想告诉Eloquent您想要与材料相关的配置文件('materials.profiles')而不是与PartBasePart相关的配置文件。您原始查询的with
等同于with(['materials', 'profiles'])
。