php - 如何构建一个查询 "get me all diplomas of which all steps are in this pivot table"?

标签 php mysql laravel laravel-5 eloquent

我的 laravel 项目中有三个模型,StepDiplomaPupil。关系如下:

class Pupil {
    function steps() {
        return $this->belongsToMany(Step::class);
    }

    function diplomas() {
        return $this->belongsToMany(Diploma::class);
    }
}

class Step {
    function diploma() {
        return $this->belongsTo(Diploma::class);
    }
}

class Diploma {
    function steps() {
        return $this->hasMany(Step::class);
    }
}

现在我有一个表单,管理员可以在其中选中学生已完成的步骤的复选框,然后我通过执行 $pupil->steps()->sync($request['steps']) 保存这些步骤;。现在我想做的是找到所有步骤都已完成的文凭并同步它们。但由于某种原因,我无法弄清楚如何构建该查询。这清楚吗?有人愿意帮忙吗?

编辑我现在有了这个,但它并不像我想要的那么干净:

class Pupil {
    public function hasCompleted(array $completedSteps)
    {
        $this->steps()->sync($completedSteps);
        $diplomas = [];

        foreach(Diploma::all() as $diploma) {
            // First see how many steps does a diploma have...
            $c1 = Step::where('diploma_id', $diploma->id)->count();
            // Then see how many of those we completed
            $c2 = Step::where('diploma_id', $diploma->id)->whereIn('id', $completedSteps)->count();

            // If that's equal, then we can add the diploma.
            if ($c1 === $c2) $diplomas[] = $diploma->id;
        }

        $this->diplomas()->sync($diplomas);
    }
}

最佳答案

不要同步文凭,因为步骤将来可能会改变,当您需要了解文凭时,通过已完成的步骤提取文凭怎么样?

class Pupil {  

    public function hasCompleted(array $completedSteps) {
        $this->steps()->sync($completedSteps);
    }

    public function getCompletedDiplomas() {
        $steps = $this->steps;
        $stepIds = // get the step ids
        $diplomaIdsFromSteps = // get the diploma Ids from the $steps

        $potentialDiplomas = Diploma::with('steps')->whereIn('id', $diplomaIdsFromSteps)->get();

        $diplomas = [];

        foreach($potentialDiplomas as $d) {
            $diplomaSteps = $d->steps;
            $diplomaStepIds = // get unique diploma ids from $diplomaSteps
            if(/* all $diplomaStepIds are in $stepIds */) {
                $diplomas[] = $d;
            }

        }

        return $diplomas;

    }
}

我还没有完成所有代码,因为我现在无法测试它。不过,我希望这能为您指明正确的方向。

关于php - 如何构建一个查询 "get me all diplomas of which all steps are in this pivot table"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34018202/

相关文章:

php - Laravel Homestead - 每个项目一个还是所有项目一个?

javascript - 图像在多图像 slider 中显示两次

python - 如何删除表中的列,其中列名是mysql中的 "index"和 "Unnamed: 0"

mysql - 寻找最接近的值。如何告诉MySQL数据已经有序了?

mysql将select中的数字值替换为另一个字符串

自升级到 5.5 以来,Laravel Forge/Envoyer 使用旧版本

php - local.ERROR : cURL error 7: Failed to connect to 127. 0.0.1 端口 7700:连接被拒绝

php - Composer : two libraries class name conflict

javascript - 通过 Ajax 将页面加载到 div 返回错误

javascript - JQuery - 每 x 次将盒子插入墙壁