我正在尝试从3个表中显示数据->
课程名称|测试名称|问题计数
课程名称1 |测试名称1 | 3
我在测试和问题1:N之间有关系
Test.php
public $table = 'Test';
protected $fillable = [
'name',
];
public function question()
{
return $this->hasMany('App\Question');
}
Question.php
public $table = 'Question';
public function test()
{
return $this->belongsTo('App\Test');
}
TestController.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
]);
}
list_course.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
我收到错误消息“此集合实例上不存在属性[问题]。”
有人可以帮我吗? 谢谢!!
答案 0 :(得分:0)
这是给您错误的原因:
TestController.php:
$courses = Course::with(['test'])->get();
$questions = $courses->question; // <---- $courses is a Collection not a Model
您正在尝试访问模型的问题属性,但是$courses
是模型的集合。
答案 1 :(得分:0)
您正在尝试访问课程模型属性,但是$courses
是Course
的集合
答案 2 :(得分:0)
您可以eager load在控制器中提问:
$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