我的 laravel 项目中有三个模型,Step
、Diploma
和 Pupil
。关系如下:
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/