一切似乎都在工作。告诉我如何修复代码,在哪里重构?
<?php
declare(strict_types = 1);
namespace Dummy;
use Illuminate\Database\Seeder;
use Database\Seeds\SequenceTrait;
use App\Models\ColdModule\ColdCustomer;
use App\Models\Tag;
class TagSeeder extends Seeder
{
use SequenceTrait;
protected $taggable = [];
/**
* Prepare all taggable classes
*
* @return void
*/
public function __construct()
{
$this->taggable = [
new ColdCustomer,
];
}
/**
* Auto generated seed file.
*
* @return void
*/
public function run(): void
{
$table = new Tag;
$tableName = $table->getTable();
\DB::table($tableName)->delete();
for ($i = 0; $i < 50; $i++) {
factory(Tag::class)->create($this->getTaggable());
}
$this->setSequence($tableName);
}
/**
* Return a randomized Model taggables.
*
* @return array
*/
protected function getTaggable(): array
{
$rand = array_rand($this->taggable);
$model = $this->taggable[$rand];
$ids = $model->pluck('id')->toArray();
$type = get_class($model);
return [
'taggable_id' => array_rand($ids),
'taggable_type' => $type,
];
}
}
我会做以下事情:
TaggableFactory
将在内容文件夹中创建一个文件factories
来填充表格之后,在
TagSeeder
在函数中,
factory
第二个参数是您需要在数据库中创建多少行的值。如果您使用 运行
seeder
,php artisan db:seed
则在DatabaseSeeder
方法中run
添加该行$this->call(TagSeeder::class);
如您所见,我删除了 table cleanup
Tag
,使用 commandphp artisan migrate:refresh --seed
,此命令将重新启动所有迁移 + 填充新数据,但如果您仍需要从表中删除行,请使用Tag::truncate();