uksarkar
5 months ago
1168
3
Eloquent

n+1 nested eager loading

Posted 5 months ago by uksarkar

I am creating a category system on my app. My category.php file like this,

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function parent()
    {
        return $this->belongsTo(self::class, 'parent_id');
    }

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

    //end of this class
}

And my database is like this,

1 name: A parent_id:0

2 name: B parent_id:1

3 name: C parent_id:2

4 name: D parent_id:3

Now I have the id = 4 and I can get the parent using $category->parent. But how can I get parents parent (if have any). Like this,

name: "D"
parent:
    name: "C"
    parent:
        name: "B"
        parent: 
            name: "A"

This code is doing the job but it's not n+1 solution

$category->where('id', 4)->with('parent.parent.parent.parent')->get();

Please sign in or create an account to participate in this conversation.