gpt4 book ai didi

laravel-5 - Laravel 多态数据库 Seeder Factory

转载 作者:行者123 更新时间:2023-12-02 22:37:09 26 4
gpt4 key购买 nike

如何为以下配置创建数据库播种器工厂?

用户

// create_users_table.php
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
...
}

// User.php
public function notes()
{
return $this->morphMany('App\Note', 'noteable');
}

复杂

// create_complex_table.php
Schema::create('complex', function (Blueprint $table) {
$table->increments('id');
...
}

// Complex.php
public function notes()
{
return $this->morphMany('App\Note', 'noteable');
}

注释

// create_notes_table.php
Schema::create('notes', function (Blueprint $table) {
$table->increments('id');
$table->integer('noteable_id');
$table->string('noteable_type');
...
}

// Note.php
public function noteable()
{
return $this->morphTo();
}

我正在努力寻找最可靠的方法来确保我不只是填充可能不存在的随机 id

最佳答案

我改进了 HyperionX 的答案并从中删除了静态元素。

$factory->define(App\Note::class, function (Faker $faker) {
$noteable = [
App\User::class,
App\Complex::class,
]; // Add new noteables here as we make them
$noteableType = $faker->randomElement($noteables);
$noteable = factory($noteableType)->create();

return [
'noteable_type' => $noteableType,
'noteable_id' => $noteable->id,
...
];
});

基本上,我们随机选择一个值得注意的类,然后调用它自己的工厂来获取值得注意的实例,从而摆脱OP答案的静态性。

关于laravel-5 - Laravel 多态数据库 Seeder Factory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49205427/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com