You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel8使用jenssegers mongodb时Product与Category的hasMany关联返回null

解决方案

核心问题

你使用了错误的关联类型:hasMany适用于关联模型中存储当前模型主键的场景,而当前你的Product模型自身存储了关联Category的ID数组,在jenssegers/laravel-mongodb扩展中需要使用belongsToMany类型完成关联。

修复步骤

  1. 修改Product模型的categories关联方法,代码如下:
public function categories() {
    return $this->belongsToMany(Category::class, null, '_id', 'category_ids');
}

参数说明:

  • 第二个参数传null:MongoDB不需要中间表,无需指定中间表名
  • 第三个参数_id:关联模型(Category)用于匹配的主键字段
  • 第四个参数category_ids:当前模型(Product)中存储关联ID的数组字段
  1. 确认两个模型继承的是jenssegers扩展的Mongo基础模型,而非Laravel默认的Eloquent模型:
// Product和Category模型顶部都需要引入对应基类
use Jenssegers\Mongodb\Eloquent\Model;

class Product extends Model
{
    // 模型其他配置
}
  1. 原查询代码无需修改,执行后即可正常获取关联的分类数据:
$product = Product::with('categories')->where('_id', $id)->first();
dd($product->categories);

原错误逻辑说明

你之前写的$this->hasMany(Category::class, 'category_ids', '_id'),会让ORM去Category集合中查找category_ids字段值等于当前Product的_id的记录,但Category集合中不存在category_ids字段,所以返回结果为空。

内容的提问来源于stack exchange,提问作者Mohammad hosein

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 23:33:01