[英]Problem with displaying data with many to many relationship in Laravel
[英]Displaying data with many to many relationship laravel 6
我是laravel 6的初學者,我只是想問問。 我想顯示數據,但沒有顯示。
index.blade.php:
@if(isset($teachers))
@foreach($teachers->qualifs as $qualif)
<li>{{ $qualif->qual }}</li>
@endforeach
@endif
Controller:
public function index()
{
$teachers= DB::table('teachers')->first();
$qualifs = DB::table('qualifs')->find($teachers->id);
return view('teachers.index',compact('teachers','qualifs'));
}
qualif.php:
public function teachers()
{
return $this->belongsToMany('todolist\teacher', 'qualif_teachers');
}
老師.php:
public function qualifs()
{
return $this->belongsToMany('todolist\qualif', 'qualif_teachers');
}
注意:數據存儲正確,僅顯示問題。
錯誤:未定義的屬性:stdClass::$qualifs
關系屬於 model 實例,這意味着 eloquent object。 當您使用查詢生成器時,您將獲得 stdObject 而不是 eloquent object。 因此你們的關系不正常。 要完成這項工作,您必須使用 eloquent 而不是查詢生成器。
public function index()
{
$teachers= teacher::get();
return view('teachers.index',compact('teachers'));
}
和視圖會像
@foreach($teachers as $teacher)
@foreach($teacher->qualifs as $qualif)
<li>{{ $qualif->qual }}</li>
@endforeach
@endforeach
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.