如何在中间 table 中获取记录及其相关数据
how to get records with its related data in intermediate table
我有两个模型,类别和品牌具有多对多关系
在类别模型中
public function brands()
{
return $this->belongsToMany(Brand::class, 'brand_category', 'category_id', 'brand_id');
}
和品牌型号
public function categories()
{
return $this->belongsToMany(Category::class, 'brand_category','brand_id','category_id' );
}
如何获得具有特定类别 ID 的品牌,例如
下面的 json
{
"data": [
{
"brand_id": 1,
"name": "Sony",
"description": null,
"logo": null,
"is_active": true,
"created_at": "2020-04-08 15:19:44",
"updated_at": "2020-04-08 15:19:44",
"deleted_at": null,
"pivot": {
"category_id": 1,
"brand_id": 1
}
},
{
"brand_id": 2,
"name": "Lg",
"description": null,
"logo": null,
"is_active": true,
"created_at": "2020-04-08 15:19:44",
"updated_at": "2020-04-08 15:19:44",
"deleted_at": null,
"pivot": {
"category_id": 1,
"brand_id": 2
}
}
],
"success": true,
"error": {
"code": 200,
"data": []
},
"message": ""
}
我想通过 wherePivot 找到一种不改变模型关系的方法...
这应该可以。
return Category::find($categoryId)->brands;
我有两个模型,类别和品牌具有多对多关系
在类别模型中
public function brands()
{
return $this->belongsToMany(Brand::class, 'brand_category', 'category_id', 'brand_id');
}
和品牌型号
public function categories()
{
return $this->belongsToMany(Category::class, 'brand_category','brand_id','category_id' );
}
如何获得具有特定类别 ID 的品牌,例如
下面的 json{
"data": [
{
"brand_id": 1,
"name": "Sony",
"description": null,
"logo": null,
"is_active": true,
"created_at": "2020-04-08 15:19:44",
"updated_at": "2020-04-08 15:19:44",
"deleted_at": null,
"pivot": {
"category_id": 1,
"brand_id": 1
}
},
{
"brand_id": 2,
"name": "Lg",
"description": null,
"logo": null,
"is_active": true,
"created_at": "2020-04-08 15:19:44",
"updated_at": "2020-04-08 15:19:44",
"deleted_at": null,
"pivot": {
"category_id": 1,
"brand_id": 2
}
}
],
"success": true,
"error": {
"code": 200,
"data": []
},
"message": ""
}
我想通过 wherePivot 找到一种不改变模型关系的方法...
这应该可以。
return Category::find($categoryId)->brands;