staudenmeir/laravel-adjacency-list

[Question] Return tree (children recursively) with relation

Closed this issue · 2 comments

What I'm trying to do: Material::with(['materialDetails.tree'])->get();
This gives (which is probably intended)
Call to undefined method Staudenmeir\LaravelAdjacencyList\Eloquent\Builder::addEagerConstraints()

Querying with descendants works, but I need it recursively (like in tree) so I can use them in resources.

My models:

class Material extends Model
{
    use HasFactory;
    use SoftDeletes;

    public $timestamps = false;
    public $guarded = [];

    public function materialDetails()
    {
        return $this->hasMany(MaterialDetails::class)->whereNull('parent_id');
    }
}
class MaterialDetails extends Model
{
    use HasFactory;
    use HasRecursiveRelationships;

    public $timestamps = false;
    public $guarded = [];
    public $with = [];
}

Hi @vatsake,
It's not possible to directly eager load a nested tree. You need to generate the tree afterwards:

$materials = Material::with(['materialDetails.descendants'])->get();

$materials->pluck('materialDetails')->collapse()->each(
    fn(MaterialDetails $materialDetails) => $materialDetails
        ->setRelation('children', $materialDetails->descendants->toTree())
);

Oh, I guess that makes sense.
Thanks.

Got it working with:

$materials = $materials->each(fn (Material $material) => $material->setRelation(
            MaterialDetails::class,
            $material->materialDetails->each(fn (MaterialDetails $details) => $details->setRelation(
                'children',
                $details->descendants->toTree()
            ))
        ));