In Laravel, how do I retrieve a random user_id from the Users table for Model Factory seeding data generation?(在 Laravel 中,如何从用户表中检索随机 user_id 以生成模型工厂种子数据?)
问题描述
目前,在我的 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.
这篇关于在 Laravel 中,如何从用户表中检索随机 user_id 以生成模型工厂种子数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Laravel 中,如何从用户表中检索随机 user_id 以生成模型工厂种子数据?
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- PHP - if 语句中的倒序 2021-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01