[版权声明] 本站内容采用 知识共享署名-非商业性使用-相同方式共享 3.0 中国大陆 (CC BY-NC-SA 3.0 CN) 进行许可。
部分内容和资源来自网络,纯学习研究使用。如有侵犯您的权益,请及时联系我,我将尽快处理。
如转载请注明来自: Broly的博客,本文链接: Laravel5.x的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; |
参考资料:《Laravel: get the last parent in nested list eloquent recursive》