Laravel Collection确定是否存在多对多关系

时间:2018-05-04 14:19:19

标签: php laravel collections model

使用Laravel 5.6,我在用户和评估(测试)之间存在多对多的关系,其中一个数据透视表称为"尝试"。我试图遍历我的所有评估并确定用户是否通过(由于失败或未进行评估(不存在关系))。

我试图使用"包含"方法,但可能没有正确使用它。

在我的User.php模型文件中,我有以下内容无法正常工作:

/*
* Relationship between User and Assessments
*/
public function assessments(){
    return $this->belongsToMany('App\Models\Assessment', 'attempts', 'user_id', 'assessment_id')->withPivot('is_passing', 'score');
}

/*
* Get all Assessments but determine if a user has passed them or not
*/
public function getPassOrFailAttribute() {
    $passed = $this->assessments->where('pivot.is_passing', 1);
    $assessments = Assessment::all();
    foreach($assessments as $assessment) {
        // *** This is the part that doesn't seem to be working correctly ***
        $assessment['passorfail'] = $assessment->contains('id', $passed->id);
    }
    return $assessments;
}

最终,我想在我的刀片视图中循环遍历所有评估,并根据用户是否通过或不合格来设置输出的样式,如下所示:

@foreach($user->passOrFail as $assessment)
    @if($assessment->passorfail)
        <div class="panel-block">
            {{ $assessment->name}}
        </div>
    @else
        <a href="{{ route('visitor.assessments.show', $assessment) }}" class="panel-block">
            {{ $assessment->name}}
        </a>
    @endif
@endforeach

感谢先进的任何帮助!

0 个答案:

没有答案