【发布时间】:2020-10-23 09:54:35
【问题描述】:
我有一个 Laravel 8 应用程序,我希望能够在执行 php artisan db:seed 时为我的一张表设置不同的状态。这是一个示例表:
Create Table: CREATE TABLE `notifications` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`message` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`is_read` tinyint(1) NOT NULL DEFAULT '0',
`recipient_role` enum('Manager','Employee') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'Manager',
`recipient_id` bigint(20) unsigned NOT NULL,
`sender_id` bigint(20) unsigned NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `notifications_recipient_id_foreign` (`recipient_id`),
KEY `notifications_sender_id_foreign` (`sender_id`),
CONSTRAINT `notifications_recipient_id_foreign` FOREIGN KEY (`recipient_id`) REFERENCES `users` (`id`),
CONSTRAINT `notifications_sender_id_foreign` FOREIGN KEY (`sender_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
在这种特殊情况下,我想使用Notification::factory 创建多个Notification 实例,其中is_read 随机设置为1 或0。我还想确保为recipient_id 和sender_id 选择了两个随机的User 实例(它们将首先播种)。这意味着我不能将它们硬编码到我的工厂中。
在实际工厂中我只填写了message:
<?php
namespace Database\Factories;
use App\Models\Notification;
use Illuminate\Database\Eloquent\Factories\Factory;
class NotificationFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Notification::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
//
'message' => $this->faker->sentence,
];
}
}
我的问题是,在NotificationSeeder.php 定义中,如何确保我有一个随机的is_read 状态以及分配给recipient_id 和sender_id 的两个不同用户?
【问题讨论】: