How does the Baum of laravel get the final parent id of a record

for example, I want to get the final parent of a little black pig with an id of 10. In this table, parent_id shows 9, but what I want to get is 5. Is there any way, or I want to judge whether a record belongs to the final parent


there are two ways to try:

  1. query out all id and parent_id, and then search so that fixed sql statements can be cached.

  2. add a new field, root_id, to record the root node, so that you don't need to search, you can query it directly, but you need to query it once when you insert it.


    $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);

* * Father-> son-> grandson->. Recursive query is defined in model (I don't think it is efficient):


protected $appends = [
    'children'
];

public function getChildrenAttribute()
{
    return $this->select('name as label', 'id')->where('parent_id', $this->attributes['id'])->get();
}
Menu