0
一對多的關係,我有以下型號Laravel雄辯許多與不同列鍵
Category
id // we don't want to use this one for the relation
category_id // we want to use this
Product
id
CategoryProduct
product_id // points to "id" on products table
category_id // points to **category_id** on categories table
我有產品型號設置如下(僅在最近的變化)。
class Product {
public function categories() {
return $this->belongsToMany('Category', 'categories_products', 'category_id');
}
}
當我試圖讓一個產品和類別如下...
Product::with('categories')->get();
我要麼是因爲查詢上categories
使用id
爲外鍵得到錯誤的類別。我需要它在分類表上使用category_id
。
或者根本沒有。我似乎無法弄清楚如何設置在belongsToMany
方法上使用哪些列。
我想你想'hasManyThrough'在這裏看到:https://laravel.com/docs/5.3/eloquent-relationships#has-many-through – Blake
的[許多人許多文檔](https://laravel.com/docs/5.2/eloquent-relationships#many-to-many)在'belongsToMany()'的每個參數位置都有一個很好的例子。嘗試'返回$ this-> belongsToMany('Category','categories_products','product_id','category_id');' – Qevo