Laravel Eloquent 从嵌套的 mysql 数据中获取 json

Laravel Eloquent get json from nested mysql data

我有这样的表格

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

我用Laravel 5.1Eloquent
如何在这样的模型中获取数据

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

有一个最好的方法。

etrepat/baum 非常棒而且简单。它具有您需要的有关嵌套元素的一切。只需将它添加到您的作曲家依赖项中即可享受。

您还可以将这些方法添加到模型中并将它们用作关系。

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

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

然后你会简单地说:

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

评论更新:

$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();