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

后端 未结 5 614
情话喂你
情话喂你 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:43

    I personally like to use.

    App\User::pluck('id')->random()
    

    Change the model name which model you want

    0 讨论(0)
  • 2020-12-29 06:50

    It does not work like that 'user_id':

    User::all()->random()->user_id
    

    But that's how it works:

    User::all()->random()->id
    
    0 讨论(0)
  • 2020-12-29 06:51

    Try the below.

    use App\User; // Assuming this is your User Model class with namespace.
    
    $factory->define(App\Reply::class, function (Faker\Generator $faker) {
      return [
        'thread_id' => 1,
        'user_id' => User::all()->random()->user_id,
        'body' => $faker->paragraph
      ];
    });
    

    Remember that this gets all the user data from your table and then choses an id randomly. So if your table has huge amount of data, it is not recommended. Instead, in your Test Case, you can create a new User (via its own factory) and assign the id to the Reply object generated from the above factory.

    Alternately, you can query for a specific user in the above factory definition.

    'user_id' => User::where('username', 'like', 'test@user.com')->get()->random()->user_id
    

    If you have a test user set up in your DB this will avoid pulling all the user data.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题