0

The last few days I've been rocking my head against the wall with the seeders. I can't seem to get the hang of it.

The relationships are very simple:

A Brand hasMany products and each product belongs to a single brand.

A Category hasMany products and each product belongs to a single category.

Given that, I'm creating 5 categories at the beginning so I can retrieve a random one later.

I'm also creating 10 brands, and for each brand I'm creating 50 products and make them belong to that brand. Then I create the relationship with the product and the category, retrieving a random category for each product.

Im getting this error:

PDOException::("SQLSTATE[HY000]: General error: 1364 Field 'brand_id' doesn't have a default value")

I dont understand why I'm getting this error because I'm creating the relationship prior to creating the products:
$brand->products()->saveMany(factory(App\Product::class, 50).

public function run()
    {
        $users = factory(\App\User::class, 1000)->create();
        $categories = factory(\App\Category::class, 5)->create();

        factory(App\Brand::class, 10)->create()->each(function ($brand) {
            $brand->products()->saveMany(factory(App\Product::class, 50)->make()->each(function ($product) use ($brand) {
                $product->category()->associate($this->getRandomCategory());
                $product->save();
            }));
        });
    }
    
    private function getRandomCategory() {
        return \App\Category::all()->random();
    }

    private function getRandomUser() {
        return \App\User::all()->random();
    }

I don't know if I'm making a big deal out of seeding but it just seems complex to me. Maybe I'm taking a wrong approach using the factories. Is there any great tutorial for seeding out there? Thanks in advance!

4

2 に答える 2

0

これは実際にはシードの問題ではありません。PDO ドライバーは、既にこの問題について通知しています。

brand_idデフォルト値がありません

おそらく Laravel は、id 列にはデフォルトが必要ないため、id を挿入しないと想定しています。しかし、列にはデータベースにデフォルトの定義がないようです (AUTO_INCREMENT のように、smth である必要があります)。これが、データベースからエラーを受け取る理由です。

于 2020-07-03T17:36:23.957 に答える
0

問題はこれでした:

各関数の実行後に saveMany メソッドが呼び出されるので、ブランド関係を追加する前に製品を保存していました。これが、foreign_key brand_id を割り当てることができなかった理由です。これは動作するコードのブロックです:

public function run()
    {
        $users = factory(\App\User::class, 1000)->create();
        $categories = factory(\App\Category::class, 5)->create();

        factory(App\Brand::class, 10)->create()->each(function ($brand) {
            $brand->products()->saveMany(factory(App\Product::class, 50)->make()->each(function ($product) use ($brand) {
                $product->category()->associate($this->getRandomCategory());

            }));
        });
    }

    private function getRandomCategory() {
        return \App\Category::all()->random();
    }

    private function getRandomUser() {
        return \App\User::all()->random();
    }
于 2020-07-04T12:33:35.913 に答える