创建一个Laravel Eloquent,如果主模型的孙子为0,则不包含返回

gr8qqesn  于 2023-04-07  发布在  其他
关注(0)|答案(1)|浏览(129)

我试图在第三层查询一个关系模型。使用下面的代码,我可以从MainModel中快速加载第三层模型数据。但是,如果3rdModel为空,则不应包括MainModel祖父。
下面是我试图处理的模型的层次结构:

MainModel
    2ndModel
        3rdModel

下面是我正在努力工作的雄辩的代码:

return $query->first_model_queries
->with('has_many_2nd_model', function ($query) use ($array_of_ids) {
    return $query->whereHas('has_many_3rd_model', function ($query) use ($array_of_ids) {
        return $query->whereIn('2ndModel_id', $array_of_ids);
    }, '=', count($array_of_ids));
});

MainModel.php
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function has_many_2nd_model()
{
    return $this->hasMany(2ndModel::class, 'first_model_id', 'id')->orderBy('id');
}

2ndModel.php
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function has_many_3rd_model()
{
    return $this->hasMany(3rdModel::class, '2nd_model_id', 'id')->orderBy('id');
}

查询值:

[
    {
        "id": 1,
        "2ndModel": [],
    },
    {
        "id": 2,
        "2ndModel": [
            {
                "id": 8,
                "3rdModel": [
                    {
                        "name": 3rdModelValue,
                    },
                ],
            }
        ],
    },
    {
        "id": 3,
        "2ndModel": [],
    },
    {
        "id": 2,
        "2ndModel": [
            {
                "id": 15,
                "3rdModel": [
                    {
                        "name": 3rdModelValue,
                    },
                ],
            }
        ],
    },
]

ID % 1和ID % 3不应再返回。

l3zydbqr

l3zydbqr1#

你可以像下面这样使用withWhereHas:

return $query->first_model_queries
    ->withWhereHas('has_many_2nd_model', function ($query) use ($array_of_ids) {
        $query->withWhereHas('has_many_3rd_model', function ($query) use ($array_of_ids) {
            $query->whereIn('2ndModel_id', $array_of_ids);
        }, '=', count($array_of_ids));
    });

相关问题