在 Laravel 中,如何从用户表中检索随机 user_id 以生成模型工厂种子数据?

2022-01-02 00:00:00 model database php laravel seed

目前,在我的 ModelFactory.php 中,我有:

Currently, in my ModelFactory.php, I have:

$factory->define(AppReply::class, function (FakerGenerator $faker) {
  return [
    'thread_id' => 1,
    'user_id' => 1,
    'body' => $faker->paragraph
  ];
});

我想从已经存储在用户表中的用户 ID 之一中生成一个随机的 user_id.我很难过,因为我不知道如何正确显示数据输出以编码,我想知道如何让 Laravel 选择一个随机用户 ID 并插入到数据库中.谢谢!:)

I would like to generate a random user_id from one of the user ID's already stored in the user table. I'm stumped because I don't know the way to display data output to code properly, and I was wondering how I would be able to allow Laravel to choose a random user ID and insert into the database. Thank you! :)

推荐答案

试试下面的方法.

use AppUser; // Assuming this is your User Model class with namespace.

$factory->define(AppReply::class, function (FakerGenerator $faker) {
  return [
    'thread_id' => 1,
    'user_id' => User::all()->random()->id,
    'body' => $faker->paragraph
  ];
});

请记住,这会从您的表中获取所有用户数据,然后随机选择一个 id.所以如果你的表数据量很大,不推荐.相反,在您的测试用例中,您可以创建一个新用户(通过其自己的工厂)并将 id 分配给从上述工厂生成的 Reply 对象.

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()->id

如果您在数据库中设置了测试用户,这将避免提取所有用户数据.

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

相关文章