雄辩的自我引用到json的hierachie

时间:2016-01-23 21:55:04

标签: php json laravel eloquent

我现在正以极高的期望尝试Eloquent。

我有一个类别树。 一切正常。但现在我想把整棵树当作json。因此,我正在做:

$categories =  Category::whereNull('parent_id')->get()->toJson();

只获取adam和eve节点。

[{"category_id":1,"name":"Boats","slug":"boats","parent_id":null},     
 {"category_id":2,"name":"Paddles","slug":"paddles","parent_id":null}]
基本上哪个好。如何递归地整合孩子?不,#34;本地人"雄辩的方式?

这样的树:

select * from categories;
+-------------+----------------+----------------+-----------+
| category_id | name           | slug           | parent_id |
+-------------+----------------+----------------+-----------+
|           1 | Boats          | boats          |      NULL |
|           2 | Paddles        | paddles        |      NULL |
|           3 | Kayaks         | kayaks         |         1 |
|           4 | Canoes         | canoes         |         1 |
|           5 | Carbon Paddles | carbon-paddles |         2 |
|           6 | Vajda K1       | vajda-k1       |         4 |
|           7 | Dagger RPM     | dagger-rpm     |         3 |
|           8 | Kober Viper    | vober-viper    |         2 |
+-------------+----------------+----------------+-----------+
8 rows in set (0.03 sec)

和那样的模型

class Category extends Eloquent {

    protected $table = 'categories';
    protected $primaryKey = 'category_id';
    protected $fillable = array("name", "slug", "parent_id");
    public $timestamps = FALSE; 

    // each category has many subcategories
    public function childs() {
        return $this->hasMany('Category');
    }

    // each category belogs to one parent category
    public function parent() {
        return $this->belongsTo('Category');
    }
}

1 个答案:

答案 0 :(得分:0)

据我所知,没有一种直接从口才获得递归结果的本地方法。 对于第一级,您将使用:

$categories = Category::whereNull('parent_id')->with('childs')->get()->toJson();

对于下一个级别(以及类似的后续内容):

$categories = Category::whereNull('parent_id')->with(['childs' => function ($query) {
        $query->with('childs');
}])->get()->toJson();

使用Lazy Eager Loading,您将能够构建自己的PHP giveMeMyCatTree()方法。

有帮助吗?