Laravel 5.5雄辩的笛卡儿

时间:2017-12-06 14:29:01

标签: php laravel-5 eloquent laravel-eloquent

我认为,我想要完成的是基于相关模型的笛卡尔结果。我希望通过热切的加载来做到这一点。

我雄辩的查询如下:

$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'的实例吗?

模型定义如下:

PartBasePart

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');
    }
}

1 个答案:

答案 0 :(得分:0)

这应该这样做:

$results = PartBasePart::whereIn('id', array(1,2,3,4,5))
                   ->with('materials.profiles')
                   ->get();

您想告诉Eloquent您想要与材料相关的配置文件('materials.profiles')而不是与PartBasePart相关的配置文件。您原始查询的with等同于with(['materials', 'profiles'])