简体   繁体   English

Laravel 8:使用工厂做种期间无法查询表

[英]Laravel 8: Unable to Query Table during Seeding Using Factory

I have a seeder:我有一个播种机:

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        $this->call([
            ArticlesTableSeeder::class,
        ]);
    }
}

The seeder itself:播种机本身:

class ArticlesTableSeeder extends Seeder
{
    public function run(): void
    {
        Article::factory()->count(10000)->create();
    }
}

My Article model has a slug column and as you may guess every time I set a slug using mutator ( setSlugAttribute($value) ) I have to query articles table to see if the given slug exists and if it does I have to generate new one and append -1 at the end, eg:我的Article model 有一个 slug 列,正如您可能猜到的那样,每次我使用 mutator ( setSlugAttribute($value) ) 设置一个 slug 时,我必须查询 articles 表以查看给定的 slug 是否存在,如果存在,我必须生成一个新的和 append -1最后,例如:

  • illo-et-et-quibusdam - first post illo-et-et-quibusdam - 第一篇文章
  • illo-et-et-quibusdam-2 - second post illo-et-et-quibusdam-2 - 第二篇文章

and so on…等等…

This all works as expected but not during the seeding, because I see that if I seed 10k of records, they don't appear on my table until all 10k are done.这一切都按预期工作,但不是在播种期间,因为我看到如果我播种 10k 的记录,它们不会出现在我的桌子上,直到所有 10k 都完成。 So when my mutator tries to query table, it doesn't see the same slug (assuming faker will generate the same one) and then after 6-7k I get:因此,当我的 mutator 尝试查询表时,它看不到相同的 slug(假设 faker 将生成相同的 slug)然后在 6-7k 之后我得到:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'illo-et-et-quibusdam' for key 'articles.articles_slug_unique' (SQL: insert into `articles`

Can I turn transactions off during seeding or is there anything I can do to fix this issue?我可以在播种期间关闭交易吗?或者我可以做些什么来解决这个问题?

The only workaround I was about to think about (that actually works) is defining quantity of records to seed, not by calling count() method on the factory, but outside of it in a loop.我要考虑的唯一解决方法(实际有效)是定义要播种的记录数量,而不是通过在工厂中调用count()方法,而是在循环之外调用它。

So instead of seeding 10k of articles like:因此,与其播种 10k 篇文章,不如:

Article::factory()->count(10000)->create();

I have to:我必须:

for ($i = 0; $i < 10000; $i++) {
    Article::factory()->count(1)->create();
}

I can obviously drop ->count(1) .我显然可以放弃->count(1)

With this I can ⌘+R in Sequel Ace or any other client and see how the number of records grow with each refresh.有了这个,我可以在 Sequel Ace 或任何其他客户端中使用 ⌘+R 并查看记录数如何随着每次刷新而增长。 This means that records are there and slug lookup works correctly, therefore avoiding dupes on unique slug index.这意味着记录在那里并且 slug 查找工作正常,因此避免了对唯一 slug 索引的重复。

Please let me know if you find a better solution.如果您找到更好的解决方案,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM