search

Home  >  Q&A  >  body text

php - How does Laravel's Baum obtain the final parent class id of a certain record?

For example, I want to get the final parent class of the little black pig with ID 10. In the table, the parent_id is 9, but what I want to get is 5. Is there any way, or I want to judge a certain item? Record whether it belongs to the final parent class

某草草某草草2734 days ago700

reply all(3)I'll reply

  • 高洛峰

    高洛峰2017-06-06 09:56:07

    Do a recursive search, and then find the one when parent_id=null

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-06-06 09:56:07

    There are 2 methods you can try:

    1. Query all ids 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 there is no need to search, just query it directly. You only need to query it once when inserting.

    reply
    0
  • 漂亮男人

    漂亮男人2017-06-06 09:56:07

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

    reply
    0
  • Cancelreply