嘗試在 Laravel 中使用多對多關系獲取資料。我的檔案和代碼如下所述。
楷模:
成績.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Grade extends Model{
protected $guarded = [];
public function specifications(){
return $this->belongsToMany(Specification::class)->withTimestamps();
}
public function gnames(){
return $this->belongsToMany(Gname::class)->withTimestamps();
}
public function gsizes(){
return $this->belongsToMany(Gsize::class)->withTimestamps();
}
}
規范.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Specification extends Model{
protected $guarded = [];
public function grades(){
return $this->belongsToMany(Grade::class)->withTimestamps();
}
public function gnames(){
return $this->belongsToMany(Gname::Class)->withTimestamps();
}
public function gsizes(){
return $this->belongsToMany(Gsize::class)->withTimestamps();
}
}
我在SpecificaitonController中的索引方法是這樣的,
public function index(Specification $specification){
$specifications = Specification::with('grades:id,grade')->first();
// dd($specifications);
return view('/home.specification.index', compact('specifications'));
}
當我 dd($specificaitons); 輸出將是,

我的目的是通過“規格和等級”模型中的多對多關系從規格和等級表中顯示“id(specification)、specification_no、id(grades)&grade”。視圖如下所示。
@forelse ($specifications as $specification)
<tbody>
<tr>
<td class="text-left">{{ $specification->id }}</a></td>
<td class="text-left">{{ $specification->specification_no }}</td>
<td class="text-left">{{ $specification->grades->grade }}</td>
<td><a href="/specifications/{{ $specification->id }}/edit">Edit</a></td>
</tr>
</tbody>
@empty
<p><strong>No data to preview</strong></p>
@endforelse
最后我以下面的錯誤告終。
ErrorException 試圖獲取非物件的屬性“id”
我嘗試了很多方法來擺脫這種混亂。我想知道我采用的是正確的方法,我們將不勝感激任何幫助來識別此錯誤。
uj5u.com熱心網友回復:
在規范模型中 public function grades(){ return $this->belongsToMany(Grade::class,'grades','id')->withTimestamps();}
uj5u.com熱心網友回復:
根據您對我的評論的回復得到了問題。在您的控制器中,您使用->first()而應該使用->get()來獲取規格集合,然后foreach/forelse在刀片中獲取該集合。
public function index(Specification $specification){
$specifications = Specification::with('grades:id,grade')->get();
return view('/home.specification.index', compact('specifications'));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/367072.html
