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

后端 未结 5 634
情话喂你
情话喂你 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 07:00

    Any class that extends Illuminate\Database\Eloquent\Model will be able to do this:

    User::inRandomOrder()->first()
    

    Or to get a Collection of 3 items:

    User::inRandomOrder()->limit(3)->get()
    

    This might be more efficient than using User::all()->first(), which ought to first query all Users.

    Your IDE (like PhpStorm) will probably be wildly confused that this is an option though.

    Also see: Laravel - Eloquent or Fluent random row

提交回复
热议问题