显示来自3个表的数据

whhtz7ly  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(203)

我正在尝试像这样显示3个表中的数据->
课程名称|测试名称|问题计数
课程名称1 |测试名称1 | 3
我把测试和问题1联系起来:n
测试.php

public $table = 'Test';

protected $fillable = [
    'name',
];

public function question()
{
    return $this->hasMany('App\Question');
}

问题.php

public $table = 'Question';

public function test()
{
   return $this->belongsTo('App\Test');
}

测试控制器.php

public function courses(Subject $subject) {
    $subject_with_courses = Subject::with(['course'])->where('id', 

    $subject['id'])->first();

    $courses = Course::with(['test'])->get();
    $questions = $courses->question;

    return view('admin.test.list_course', [
        'courses' => $courses,
        'questions' => $questions,
        'subject' => $subject
    ]);
}

列表\课程.php

@foreach($courses as $course)
    <tr>
        <td>
            {{ $course->name }}
        </td>
        <td>
            @foreach($course->test as $test)
                {{ $test->name }}
            @endforeach
        </td>
        <td>
            @foreach($course->questions as $test)
                {{ $test->count() }}
            @endforeach
        </td>
    </tr>
@endforeach

i get error“此集合示例上不存在属性[问题]。”
有人能帮我吗?谢谢您!!

g52tjvyc

g52tjvyc1#

您可以在控制器中加载问题:

$courses = Course::with(['test', 'test.question'])->get();

这些问题属于考试而不是课程,所以你不能打电话 $course->question 在课程模式上。
在你看来:

@foreach($courses as $course)
    <tr>
        <td>
            {{ $course->name }}
        </td>

        <td>
            @foreach($course->test as $test)
                {{ $test->name }}
            @endforeach
        </td>

        <td>
            @foreach($course->test as $test)
                {{ $test->question->count() }}
            @endforeach
        </td>
    </tr>
@endforeach
hzbexzde

hzbexzde2#

这就是导致错误的原因:
testcontroller.php:

$courses = Course::with(['test'])->get();
$questions = $courses->question; // <---- $courses is a Collection not a Model

您正在尝试访问模型的questions属性,但是 $courses 是模型的集合。

qoefvg9y

qoefvg9y3#

您正在尝试访问课程模型属性,但是 $courses 是的集合 Course

相关问题