Laravel框架下如何从指定Department获取全部Product?
实现Department模型直接获取下属全部Product的方法
背景说明
现有三张数据表:Departments、Categories、Products,关联关系如下:
- 一个Department可包含多个Category,一个Category仅归属一个Department
- Category与Product为多对多关联
现有模型代码:
class Department { public function categories(){ return $this->hasMany(Category::class); } } class Category{ public function department(){ return $this->belongsTo(Department::class); } public function products(){ return $this->belongsToMany(Product::class,"product_category"); } }
需求
实现通过$department->products直接获取指定Department下的全部Product。
解决方案
在Department模型中添加products关联方法,以下是两种常用实现:
方式一:闭包关联查询(简单直观)
class Department { public function categories(){ return $this->hasMany(Category::class); } // 新增products关联方法 public function products() { return Product::whereHas('categories', function ($query) { $query->where('department_id', $this->id); }); } }
使用示例:
$department = Department::find(1); $products = $department->products; // 获取该部门下所有产品 // 也支持添加额外查询条件 $cheapProducts = $department->products()->where('price', '<', 50)->get();
方式二:完整Eloquent关联(支持预加载)
这种方式定义符合Eloquent规范的关联,可使用预加载避免N+1查询问题:
class Department { public function categories(){ return $this->hasMany(Category::class); } // 新增products关联方法 public function products() { return $this->belongsToMany(Product::class, 'categories', 'department_id', 'id') ->join('product_category', 'categories.id', '=', 'product_category.category_id') ->select('products.*') ->distinct(); } }
使用示例:
// 预加载products,优化查询 $department = Department::with('products')->find(1); $products = $department->products;
内容的提问来源于stack exchange,提问作者YASSINE BENAID
相关产品推荐
相关产品推荐

