Laravel 10 ORM一对多关联:无法获取商品分类名称问题
问题解决:Laravel关联无法获取分类名称
错误分析
你的关联关系定义存在两处错误,导致无法正确加载分类数据:
Product模型的关联外键错误
belongsTo方法的第二个参数应该是当前模型(Product)中存储关联模型ID的外键字段,你错误地写了'id',这会导致Laravel用Product的id去关联ProductCategory,逻辑完全错误。ProductCategory模型的关联外键错误
hasMany方法的第二个参数应该是关联模型(Product)中的外键字段,你写了'product_category_id',但你的Product模型中实际外键字段是product_category(从$fillable配置可看出),字段不匹配导致关联失效。
修正步骤
1. 修正Product模型的关联
class Product extends Model { use HasFactory; protected $fillable = ['branch_id', 'product_category', 'product_name', 'product_slug']; public function productCategory() { // 第二个参数改为Product表中的外键字段product_category return $this->belongsTo(ProductCategory::class, 'product_category'); } }
2. 修正ProductCategory模型的关联
class ProductCategory extends Model { use HasFactory; protected $fillable = ['branch_id', 'category_name', 'is_visible', 'display_order']; public function products() { // 第二个参数改为Product表中的外键字段product_category return $this->hasMany(Product::class, 'product_category'); } }
3. 优化查询(可选,减少冗余数据加载)
如果只需要商品ID、名称和分类名称,可以指定查询字段,避免加载不必要的数据:
// 必须包含关联外键字段,同时指定关联模型需要的字段(需包含主键id,否则关联无法匹配) $products = Product::with('productCategory:id,category_name') ->get(['id', 'product_name', 'product_category']);
4. 输出目标格式
遍历查询结果,输出你需要的列表格式:
foreach ($products as $index => $product) { echo ($index + 1) . ". " . str_pad($product->product_name, 15) . " " . $product->productCategory->category_name . "\n"; }
额外说明
如果你实际商品表的外键字段是你开头提到的category_id(而非模型中的product_category),需要同步修改:
- Product模型的
$fillable替换为'category_id' - 关联代码调整为:
// Product模型 public function productCategory() { return $this->belongsTo(ProductCategory::class, 'category_id'); } // ProductCategory模型 public function products() { return $this->hasMany(Product::class, 'category_id'); }
内容的提问来源于stack exchange,提问作者flutternewbie
相关产品推荐
相关产品推荐

