Factory and seeds in laravel

-2

Greetings guys, I want to do the following:

  • Relate users with profiles
  • Relate posts to users
  • Relate categories to posts

I have created 4 tables Usuarios , Perfiles , Posts and Categorias

And I want to fill the database using the factory of laravel 5 and that these data are already related to each other !! and a brief documentation of the code,

  

I have seen something in the documentation, but I do not have it very clear.

    
asked by Franklin'j Gil'z 15.03.2017 в 02:36
source

1 answer

0

I have solved my problem. I know there is another method, but this one worked for me at the moment.

I know I asked for the relationship with several tables, but in this case it applies the same as for all.

In the function run of DatabaseSeeder.php I placed this

$this->call(ProfilesTableSeeder::class);
$this->call(UsersTableSeeder::class);
  

It is important to first call the seed of the profiles and then the user profile, since there can not be a user without a profile

in UsersTableSeeder use the following factory

$factory->define(App\User::class, function (Faker\Generator $faker) {

    $p = []; // Array para guardar los id's de los perfiles
    $profiles = App\Profile::get(['id']); // Consulta de los Perfiles (Si no colocamos el Seed de perfiles primero, esta linea traera datos vacios ya que no se han creado los perfiles)
    foreach ($profiles as $k => $v) {
        $p[] = $v->id; // añadimos el valor al array
    }
    return [
        /*
         * El método 'randomElement' recibe por parametro un array y escoje un valor aleatorio 
         */
        'profile_id' => $faker->randomElement($p)
    ];
});
    
answered by 15.03.2017 / 04:37
source