我有類別 - 課程資料透視表。它被稱為方向:
public $table = 'directions';
protected $fillable = [
'course_category_id','course_id'
];
類別:
public function manyCourses()
{
return $this->belongsToMany(Direction::class, 'directions', 'course_category_id', 'course_id');
}
課程:
public function manyCategories()
{
return $this->belongsToMany(Direction::class, 'directions', 'course_id', 'course_category_id');
}
在刀片中,我試圖從方向表中獲取資料,但我收到錯誤語法錯誤或訪問沖突:1066 Not unique table/alias I searched error,它告訴我有關系問題......但我想我'我在刀片中做錯了什么......
<select class="many-course-category" name="categoryId" multiple="multiple">
@foreach ($c->manyCategories as $category)
<option value="{{ $category->pivot->course_category_id }}">
{{ $category->pivot->course_category_id->name }}
</option>
@endforeach
</select>
$c 是我目前的課程/課程編輯...
所以我做錯了什么?
uj5u.com熱心網友回復:
你在宣告這種關系是錯誤的。語法是
belongsToMany($related, $table, $foreignPivotKey, $relatedPivotKey)
$related 不是樞軸模型,而是相關模型。
要指定樞軸模型的類,您需要將using()方法鏈接到您的關系。(檔案)。您可能需要在其宣告 ( class Direction extends Pivot) 中讓您的 Direction 模型擴展 Pivot 而不是 Model
指定樞軸模型是可選的。
public function manyCourses()
{
return $this->belongsToMany(Course::class, 'directions', 'course_category_id', 'course_id')
->using(Direction::class);
}
public function manyCategories()
{
return $this->belongsToMany(Category::class, 'directions', 'course_id', 'course_category_id')
->using(Direction::class);
}
至于刀片部分,就像Erich建議的那樣,解決方案是呼叫$category->name.
@foreach ($c->manyCategories as $category)
<option value="{{ $category->pivot->course_category_id }}">
{{ $category->name }}
</option>
@endforeach
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/407945.html
標籤:
上一篇:Laravel,連接后查詢連接表
下一篇:向stdClass物件添加更多值
