我有產品型號,我有類別型號。我也有一個名爲category_product
的數據透視表。我試圖在我的CategoryController上設置一個orderBy
。Laravel - 如何使用雄辯在FK上設置orderBy?
Product.php
public function category()
{
return $this->belongsToMany(Category::class, 'category_product', 'category_id', 'product_id');
}
Category.php
public function products()
{
return $this->hasMany(Product::class);
}
CategoryController.php
public function index()
{
// works
$categories = Category::where('parent_category_id', 0)->orderBy('name', 'asc')->get();
// Unknown column 'category_product.sort_key'
$categories = ProductCategory::where('parent_category_id', 0)->orderBy('category_product.sort_key', 'asc')->orderBy('name', 'asc')->get();
return view('category.index', compact('categories'));
}
我數據透視表如下所示:
product_id
category_id
sort_order
我遵循建議的表命名約定。我甚至傳遞了透視表名稱以保證安全。 - 我不知道如何在我的查詢中包含數據透視表。
我也相信這是我無法正確訪問列的原因。 例如:
Product.php
$this->categories->myColumn // Undefined property
我的遷移是這樣的:
...
$table->foreign('product_id')->references('id')->on('products');
$table->foreign('category_id')->references('id')->on('categories');
謝謝你的任何建議!
編輯
我已經更新了邏輯的建議,我仍然不認爲我已經得到了參加完全正確呢。
Category.php
public function products()
{
return $this->belongsToMany(Product::class, 'category_product', 'category_id', 'product_id')
->withPivot('sort_key');
}
Product.php
public function categories()
{
return $this->belongsToMany(Category::class, 'category_product', 'category_id', 'product_id')
->withPivot('sort_key');
}
CategoryController.php
public function index()
{
$categories = Category::where('parent_category_id', 0)
->orderBy('sort_order', 'asc')
->orderBy('name', 'asc')
->get();
return view('category.index', compact('categories'));
}
Column not found: 1054 Unknown column 'sort_order' in 'order clause
如果我參加了->orderBy('sort_order', 'asc')
一切都很好。我也試過->orderBy('category_product.sort_order', 'asc')
,沒有運氣。
非常感謝你的詳細解答亞歷克斯!我仍然遇到一些麻煩 - 我已經在上面編輯了我的問題。 – Damon