I'm using nested set version 6.0.0 on laravel v7.30.4, I added columns to migration:
Schema::table('companies', function (Blueprint $table) {
$table->nestedSet();
});
And this is how I create parent and child nodes:
$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());
and migrated, then when I insert anything in the table, regardless of setting its parent Id or not, it is overwritten to null. _lft and _rgt are set to values but those values don't seem to make a tree.
Company model:
class Company extends Model implements \JsonSerializable
{
use NodeTrait;
/**
* The attributes that are mass assignable.
*
* @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(),
];
}
}
Edit: Well, somehow I fixed it :D I already had a parent_company_id in my table, and it was a foreign key to this table itself. I deleted this column and just used the nestedset parent_id column, it got fixed and now all parent Ids are setting correctly.