我现在正以很高的期望尝试雄辩。
我有一个类别树。一切正常。但是现在我想将整个树作为 json 返回。因此,我正在做:
$categories = Category::whereNull('parent_id')->get()->toJson();
并且只获取亚当和夏娃节点。
[{"category_id":1,"name":"Boats","slug":"boats","parent_id":null},
{"category_id":2,"name":"Paddles","slug":"paddles","parent_id":null}]
这基本上很好。如何递归地整合孩子?没有"本土"雄辩的方式吗?
像这样的树:
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');
}
}
据
我所知,没有原生方法可以直接从 eloquent 获得递归结果。对于第一级,您将使用:
$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 Load,您将能够构建自己的PHP giveMeMyCatTree()
方法。
这有帮助吗?