D
D
danilaka252020-07-13 20:51:55
recursion
danilaka25, 2020-07-13 20:51:55

Laravel: How to populate a base with a faker, taking into account the user nesting level limit?

I fill the database with two seeders.

This is how the database looks like after the first
5f0c9a7a25332779606724.png
Admin seeder, everything is 0.

I need to assign the second seeder to each admin user, but so that the nesting level does not exceed 7.

public function run()
    {
        $faker = Faker\Factory::create('uk_UA');
        $limit = 501;

        for ($i = 1; $i < $limit; $i++) {                
           $employees = Employee::find($i);
           if ($i == 1) { //admin сам себе admin
            $head_id = 1;
           } else {
            $head_id = $this->check_admin($i);
           }
           $employees->head_id = $head_id;
           $employees->save();
        }
    }

    public function check_admin($current_user) {

        while(in_array( ($rand_id = random_int(1,500)), array($current_user) ) ); // exept own id
        $deleteSybm = ["[", "]"]; // не обращать внимания
        $head_id = str_replace(  $deleteSybm, '' , Employee::where('id', $rand_id)->pluck('head_id')); 
   
        $count_level = $this->count_level($rand_id, 0); 

        if ($head_id == 0) {
            return  $rand_id;
        }

        if ($count_level == "false_out") { // больше 7               
            return $this->check_admin($current_user); // with return goes OUT
        } else {
            return  $rand_id;
        } 
    } 
    public function count_level($rand_id, $level) {       
            
            $max_lavel = 7;    
            $deleteSybm = ["[", "]"]; // не обращать внимания
            $head_id = str_replace(  $deleteSybm, '' , Employee::where('id', $rand_id)->pluck('head_id'));                            
                    
            if($level >= $max_lavel) {            
                return "false_out";
            }  

            $level++;
            return $this->count_level($head_id, $level);                      
        }
    }


It seems not difficult
We generate a random id, look at the user with this id, see if he has an admin, if not, assign a random id, if there is, then we count further, if this is repeated more than 7, we return to the first paragraph

But for some reason I don’t care after second seedera nesting level
5f0c9d93ae894199485819.png

exceeded

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dimonchik, 2020-07-14
@dimonchik2013

nothing is clear
throw everything away and leave the question about the relationship admin - not admin - recursion

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question