2 回答

TA貢獻1811條經(jīng)驗 獲得超5個贊
你可以利用口才和關系。在您的 ProductCategory 模型上執(zhí)行以下操作:
public function product(){
return $this->belongsTo('App\Product', 'productId')
}
public function category(){
return $this->belongsTo('App\Category', 'categoryID')
}
然后你可以像這樣查詢:
ProductCategory::with(['product','category'])->where('categoryId', 191)->get();

TA貢獻1825條經(jīng)驗 獲得超4個贊
您可以通過在模型中定義關系來實現(xiàn)它,如下所示:
在您的產(chǎn)品模型中定義類別函數(shù)
public function categories() {
return $this->belongsToMany(Category::class, 'product_categories', 'productId', 'categoryId');
}
類別模型中的相似性定義了產(chǎn)品的關系
public function products() {
return $this->belongsToMany(Product::class, 'product_categories', 'categoryId', 'productId');
}
在本例中,product_categories 表是一個數(shù)據(jù)透視表,數(shù)據(jù)透視表需要遵循一些規(guī)則:
數(shù)據(jù)透視表應該是兩個表的單數(shù)名稱,在您的情況下它應該是product_category表
數(shù)據(jù)透視表命名約定應該按字母順序排列,在您的情況下它應該是category_product
無需在 ppivot 表中創(chuàng)建 id 和 timestamps 列
您實際上不需要為數(shù)據(jù)透視表創(chuàng)建模型
另外,這不是規(guī)則,而是建議,您的表列應該是蛇形大小寫,例如category_id
在模型中定義這些函數(shù)后,您可以按如下方式訪問相關數(shù)據(jù):
$product = Product::find(27); //finding product by id
$product->categories;
$category = Category::find(187); //finding category by id
$category->products;
- 2 回答
- 0 關注
- 154 瀏覽
添加回答
舉報