Eloquent:约束一个渴望的负载关系,其中关系属性为0或关系不存在

时间:2016-02-11 14:22:21

标签: php laravel eloquent

我希望获得所有Report模型,ReportUpload的{​​{1}}属性等于0 status 1}}关系不存在。 ReportUploadReport模型具有一对一关系,ReportUpload属于ReportUpload

有些不确定如何使用雄辩的关系约束或任何其他方法来解决这个问题。任何帮助将不胜感激。

这是我目前的代码:

Report

代码无法产生预期效果。

修改

尝试这种方法,但不确定它是否正确:

// initial query

$reports = Report::whereHas('link', function($query) {
        $query->where('status', 'complete');
    })->with('student', 'course', 'institution', 'reportUpload');


// apply constraint

if ($request->has('uploadStatus')) {
    $uploadStatus = $request->has('uploadStatus'); // 0 or 1

    if ($uploadStatus === 0) {
        $reports = $reports
            ->whereDoesntHave('reportUpload')
            ->orWhereHas('reportUpload', function($query) use ($uploadStatus) {
                $query->where('status', $uploadStatus);
            });
    } else {
        $reports = $reports->whereHas('reportUpload', function($query) use ($uploadStatus) {
            $query->where('status', $uploadStatus);
        });
    }
}

2 个答案:

答案 0 :(得分:6)

首先,您的初始代码存在一些错误。

1 - 您正在检查请求has是否为uploadStatus。然后,$uploadStatus == $request->has始终为true

if ($request->has('uploadStatus')) {
    $uploadStatus = $request->has('uploadStatus');

所以我想你可能想要:

if ($request->has('uploadStatus')) {
    $uploadStatus = $request->input('uploadStatus');

2 - 您严格比较$uploadStatus === 0这可能不起作用,因为请求可能会返回字符串'0'而不是整数,因此您应该与==或cast {进行比较{1}}至$uploadStatus

在此之后,我认为您在问题中添加的代码按预期工作:

(int)

因为封装查询的$reports = $reports ->where(function ($query) use ($uploadStatus) { $query ->whereDoesntHave('reportUpload') ->orWhereHas('reportUpload', function($query) use ($uploadStatus) { $query->where('status', $uploadStatus); }); }); 会将它放在括号之间。

答案 1 :(得分:1)

尝试分隔查询。 whereDoesntHave即使是orWhereHas语句,or可能会对此进行负数计算:

$reportsNoUpload = $reports
            ->whereDoesntHave('reportUpload')->get();

$reportsIncomplete = $reports
            ->orWhereHas('reportUpload', function($query) use ($uploadStatus) {
                $query->where('status', $uploadStatus);
            })->get();

$reports = $reportsNoUpload->merge($reportsIncomplete);