为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
隔江千里 2019-03-13 07:00:19
譬如我想获得id为10的小黑猪的最终父类,在该表格中parent_id显示的是9,但我想获得的是5,请问有没有什么办法,或者说我想判断某一条记录是否属于该最终父类
查看完整描述

3 回答

?
交互式爱情

TA贡献1712条经验 获得超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);
查看完整回答
反对 回复 2019-03-18
?
白衣染霜花

TA贡献1796条经验 获得超10个赞

** 父->子->孙->..... 递归查询,在model中定义一下(个人觉得效率不行):


protected $appends = [
    'children'
];

public function getChildrenAttribute()
{
    return $this->select('name as label', 'id')->where('parent_id', $this->attributes['id'])->get();
}
查看完整回答
反对 回复 2019-03-18
  • 3 回答
  • 0 关注
  • 681 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信