M
M
madc0de2020-03-07 23:56:19
Laravel
madc0de, 2020-03-07 23:56:19

How to add no more than 4 identical values ​​in a specific table in Laravel Faker?

Good day!

I generate users through a faker

$factory->define(Users::class, function (Faker $faker) {

    $teamIds = Team::pluck('id')->toArray();
    
    return [
        'id_team' => $faker->randomElement($teamIds),
        'name' => $faker->name,
        'photo' => $faker->image('/tmp', 400, 400, 'cats'),
        'role' => rand(0,1)
    ];
});


How do I get 5 people on each team? That is, you need to generate 5 users for each team.
Also `role` requires that only 5 users have role '1'.

Is it possible to implement this or will it be necessary to form values ​​\u200b\u200bthrough a loop and then write them down. Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2020-03-13
@madc0de

database/seeds/TeamSeeder.php

factory(Team::class, 3)->create()->each(function($team) {
    $team->users()->saveMany(factory(Users::class, 5)->make());
});
// Roles
$admin_ids = collect(range(1, Users::count()))->random(5)->toArray();
Users::whereIn('id', $admin_ids)->update(['role' => 1]);

It will work if you have a hasMany relationship with the Users model for the Team model.
PS: I recommend using Laravel standards:
Users -> User
id_team -> team_id

K
Konstantin B., 2020-03-08
@Kostik_1993

You need to generate teams first, and already add participants to the teams,
you do the opposite

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question