paranoid
paranoid

Reputation: 7105

Laravel Eloquent get json from nested mysql data

I have tabel like this

id  name         parent_id     order_id
1   software       0             1
2   hardware       0             2
3   windows        1             3
4   linux          1             4
5   mouse          2             5
6   keyword        2             6

And I use Laravel 5.1 Eloquent
How to get data in model like this

[{"id":1,"children":[{"id":3},{"id":4}]},{"id":2,"children":[{"id":5},{"id":6}]}]

Upvotes: 0

Views: 528

Answers (1)

Ozan Kurt
Ozan Kurt

Reputation: 3866

There is a best way to do this.

The package etrepat/baum is so awesome and easy. It has everything you need about nesting elements. Just add it to your composer dependencies and enjoy.

You can also add these methods to your Model and use them as relations.

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

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

Then you will simply say:

$results = MyModel::with('children')->get();

Update for comment:

$results = Category::select('id','name')->with([
    'children' => function($query) {
        $query->select('id', 'parent_id'); 
        // You can customize the selected fields for a relationship like this.
        // But you should select the `key` of the relationship. 
        // In this case it's the `parent_id`.
    }
])->get();

Upvotes: 1

Related Questions