In Laravel, how do I retrieve a random user_id from the Users table for Model Factory seeding data generation?

后端 未结 5 648
情话喂你
情话喂你 2020-12-29 06:41

Currently, in my ModelFactory.php, I have:

$factory->define(App\\Reply::class, function (Faker\\Generator $faker) {
  return [
    \'thread_id\' => 1,
         


        
5条回答
  •  滥情空心
    2020-12-29 06:57

    It may not be that efficient but you can use it:

    User::all('id')->random();

    or

    rand(1,User::count());

    or

    User::inRandomOrder()->limit(1)->get();

    First one will be more faster than User::all()->random()->id; because that all function by default gets '*' as column name parameter. So, it will get all the columns for all the rows.

提交回复
热议问题