Laravel5 的 Eloquent 返回树形结构

有时候要做树形结构,Laravel 的 Eloquent 可以很方便地递归查询,并返回结果。

创建 MySQL 表:

1
2
3
4
5
6
7
8
CREATE TABLE `sample` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`parent_code` varchar(45) NOT NULL DEFAULT '0',
`code` varchar(45) NOT NULL DEFAULT '',
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `code_UNIQUE` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

创建 Model:sample.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Sample extends Model {
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'sample';

public function parent() {
return $this->belongsTo('App\Models\Sample', 'parent_code', 'code');
}

public function parents() {
return $this->parent()->with('parents');
}

public function child() {
return $this->hasMany('App\Models\Sample', 'parent_code', 'code');
}

public function children() {
return $this->child()->with('children');
}
}

使用方法: 返回本身和子节点

1
2
3
$model = \App\Models\Sample::find(1);
$model->children = $model->children;
return $model;

返回仅子节点

1
\App\Models\Sample::find(1)->children;

参考资料