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

Laravel 8 自引用hasManyThrough关联查询返回空集问题排查

问题原因与解决方案

你当前的hasManyThrough关联参数配置错误,导致关联查询条件不匹配,所以返回空集合。

Laravel hasManyThrough 方法的核心参数顺序和含义如下:

hasManyThrough(目标模型类, 中间模型类, 中间表关联当前模型的外键, 目标模型关联中间表的主键, 当前模型的主键, 中间表关联目标模型的外键)

你原有代码的错误点:

  • 第三个参数错误传入了child_product_id,会导致Laravel查询中间表时匹配child_product_id = 当前父产品ID的记录,和你的实际业务逻辑完全相反,自然匹配不到任何数据。

方案1:调整hasManyThrough关联参数

将Product模型的childs关联调整为如下写法即可:

public function childs()
{
    return $this->hasManyThrough(
        self::class,
        ProductRelation::class,
        'parent_product_id', // 中间表关联父产品的外键
        'id', // 子产品表的主键
        'id', // 当前父产品的主键
        'child_product_id' // 中间表关联子产品的外键
    );
}

方案2:使用更适配场景的belongsToMany关联

你当前的产品父子从属是典型的自引用多对多关联,不需要额外定义中间表模型,直接用belongsToMany写法更简洁:

class Product extends Model
{
    protected $primaryKey = 'id';
    protected $table = 'products';
    
    public function childs()
    {
        return $this->belongsToMany(
            self::class,
            'product_relations',
            'parent_product_id',
            'child_product_id'
        );
    }
}

调整后原查询代码$childs = Product::find(1)->childs()->get();即可正确返回ID为1的产品关联的Mouse、VGA两个子产品。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 18:06:03