Pivot 的工厂和播种机 Table

Factory & Seeder for Pivot Table

我正在尝试为枢轴创建工厂和播种机 table。我试图这样做而不只是为枢轴 table 创建模型。但是,这样做时,我遇到了错误。在显示错误之前,这是我的文件:

// CategoryNewsFactory.php
use App\Model;
use Faker\Generator as Faker;

$factory->define(Model::class, function (Faker $faker) {
    DB::table('category_news')->insert(
      [
          'category_id' => factory(App\Category::class)->create()->id,
          'news_id' => factory(App\News::class)->create()->id,
      ]
  );
});
// CategoriesNewsSeeder.php

    public function run()
    {
        factory(App\Model::class, 35)->create();
    }

这是我的错误信息:

   Error

  Class 'App\Model' not found

  at C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:232
    228|         if ($this->amount < 1) {
    229|             return (new $this->class)->newCollection();
    230|         }
    231|
  > 232|         $instances = (new $this->class)->newCollection(array_map(function () use ($attributes) {
    233|             return $this->makeInstance($attributes);
    234|         }, range(1, $this->amount)));
    235|
    236|         $this->callAfterMaking($instances);

  1   C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:169
      Illuminate\Database\Eloquent\FactoryBuilder::make([])

  2   C:\laragon\www\startup-reporter\database\seeds\CategoriesNewsTableSeeder.php:14
      Illuminate\Database\Eloquent\FactoryBuilder::create()

所以我想知道,我做错了什么,我该如何解决?

谢谢。

首先,您可以创建the model for your pivot table as far as Model class (in your case) doesn't exist at all. Secondly, you can attach/sync one model to another instead of creating a pivot record manually. Finally, you can use the following code inside factory(App\Category::class)

$factory->afterCreating(Category::class, function (Category $category, $faker) {
    $category->news()->save(factory(News::class)->make());
});