laravel的Baum怎么获得某一条记录的最终父类id

譬如我想获得id为10的小黑猪的最终父类,在该表格中parent_id显示的是9,但我想获得的是5,请问有没有什么办法,或者说我想判断某一条记录是否属于该最终父类

https://img.mukewang.com/5c8f417a00012bc308000216.jpg

隔江千里
浏览 682回答 3
3回答

交互式爱情

$arr = array( array( 'id' => 10, 'parent_id' => 9 ), array( 'id' => 9, 'parent_id' => 5 ), array( 'id' => 5, 'parent_id' => null ), ); function getParentId($arr, $id = 10) { foreach ($arr as $val) { if($val['id'] == $id) { if(!empty($val['parent_id'])) { $id = $val['parent_id']; getParentId($arr, $id); }else { return $id; } } } return $id; } echo getParentId($arr, 10);

白衣染霜花

** 父->子->孙->..... 递归查询,在model中定义一下(个人觉得效率不行): protected $appends = [ 'children' ]; public function getChildrenAttribute() { return $this->select('name as label', 'id')->where('parent_id', $this->attributes['id'])->get(); }
打开App,查看更多内容
随时随地看视频慕课网APP