[英]Laravel Eloquent many to many relationship with different column as key
我有以下型號
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
方法上使用哪些列。
嘗試以下操作,
class Product {
public function categories() {
return $this->belongsToMany('Category', 'categories_products', 'product_id','category_id');
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.