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

使用lazychaser/laravel-nestedset保存模型后parent_id字段被置为null

Laravel nested set扩展异常问题及解决

环境与前置配置

我在Laravel v7.30.4版本中使用6.0.0版本的nested set扩展,迁移文件中添加了如下字段配置:

Schema::table('companies', function (Blueprint $table) {
            $table->nestedSet();
        });

节点创建逻辑

我通过以下方式创建父子节点:

$parentCompany = factory(Company::class)->create();
$childrenCompanies = $parentCompany->children()->saveMany(factory(Company::class)->times(2)->make());
($childrenCompanies[0])->children()->saveMany(factory(Company::class)->times(3)->make());
($childrenCompanies[1])->children()->saveMany(factory(Company::class)->times(2)->make());

问题现象

执行迁移后向表中插入数据时,无论是否手动设置parent Id,最终该字段都会被覆盖为null;_lft和_rgt字段虽有生成值,但数值无法组成正确的树形结构。

关联模型代码

Company模型代码如下:

class Company extends Model implements \JsonSerializable
{
    use NodeTrait;

    /**
     * 可批量赋值的属性
     *
     * @var array
     */
    protected $fillable = [
        'name'
    ];

    public function stations()
    {
        return $this->hasMany(Station::class);
    }

    public function parent()
    {
        return $this->belongsTo(Company::class, 'parent_company_id');
    }

    public function children()
    {
        return $this->hasMany(Company::class, 'parent_company_id');
    }

    public function jsonSerialize()
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'createdAt' => $this->created_at->toAtomString(),
            'updatedAt' => $this->updated_at->toAtomString(),
            'parentCompany' => $this->parent()->get(),
        ];
    }
}

问题根因与解决方法

问题已成功解决,根因为原表中预先存在自关联外键字段parent_company_id,与nested set扩展默认使用的parent_id父级关联字段冲突,导致扩展的赋值逻辑异常。删除自定义的parent_company_id字段,直接使用nestedset自带的parent_id字段后,parent_id赋值逻辑恢复正常,_lft、_rgt字段也会生成符合树形结构的正确数值。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 08:57:02