Laravel中通过中间表查询指定分类下所有产品的问题
解决方案
首先确认你的模型关联是否正确配置,以下是匹配你表结构的关联定义:
模型关联代码
Categorie 模型
namespace App\Models; use Illuminate\Database\Eloquent\Model; class Categorie extends Model { protected $table = 'categories'; // 根据实际表名调整,Laravel默认使用复数表名 public function sousCategories() { return $this->hasMany(SousCategorie::class, 'categorie_id'); } // 定义 HasManyThrough 关联,直接从分类关联到产品 public function produits() { return $this->hasManyThrough( Produit::class, SousCategorie::class, 'categorie_id', // Sous_categorie表关联Categorie的外键 'sous_categorie_id', // Produit表关联Sous_categorie的外键 'id', // Categorie表的主键 'id' // Sous_categorie表的主键 ); } }
SousCategorie 模型
namespace App\Models; use Illuminate\Database\Eloquent\Model; class SousCategorie extends Model { protected $table = 'sous_categories'; public function categorie() { return $this->belongsTo(Categorie::class, 'categorie_id'); } public function produits() { return $this->hasMany(Produit::class, 'sous_categorie_id'); } }
Produit 模型
namespace App\Models; use Illuminate\Database\Eloquent\Model; class Produit extends Model { protected $table = 'produits'; public function sousCategorie() { return $this->belongsTo(SousCategorie::class, 'sous_categorie_id'); } }
两种查询指定分类下产品的方法
方法1:通过 Categorie 模型直接获取(推荐,利用 HasManyThrough 关联)
如果仅需获取该分类下的所有产品,直接通过分类模型的关联查询:
$categorieId = $id; // 你的目标分类ID $produits = Categorie::findOrFail($categorieId)->produits;
如果需要同时加载产品对应的子分类和分类信息:
$produits = Categorie::with('produits.sousCategorie.categorie') ->findOrFail($categorieId) ->produits;
方法2:从 Produit 模型出发,通过关联筛选
如果必须从产品模型开始查询,使用 whereHas 方法筛选关联子分类所属的分类ID:
$categorieId = $id; $produits = Produit::with('sousCategorie.categorie') ->whereHas('sousCategorie', function ($query) use ($categorieId) { $query->where('categorie_id', $categorieId); }) ->get();
错误原因说明
你之前的 where('categorie_id', 'like', '%'.$id.'%') 报错,是因为Produit 表本身不存在 categorie_id 字段,该字段仅存在于 Sous_categorie 表中。直接在 Produit 查询上添加该条件时,Laravel 会尝试在 produits 表中查找这个字段,因此抛出了字段不存在的错误。
内容的提问来源于stack exchange,提问作者MOHAMED KESSOUM
相关产品推荐
相关产品推荐

