简体   繁体   中英

how to seed one to many relationship in laravel 7

I have this migrations and I want to see them using a factory model

migration category:

    Schema::create('categories', function (Blueprint $table) {
        $table->id('id_cat');
        $table->string('nom');

    });

migration marque:

        Schema::create('marques', function (Blueprint $table) {
        $table->id('marque_id');
        $table->foreignId('cat_id')->constrained();
        $table->string('designation');
    });

when I run this factory model it doesnt work

category factory:

$factory->define(Category::class, function (Faker $faker) {
return [
    'nom' => $faker->unique()->word
];

});

marque factory:

$factory->define(Marque::class, function (Faker $faker) {
return [
    'cat_id' => Category::all()->random()->id,
    'designation'=>$faker->unique()->word
];

});

You have to make sure that your model property fillable mass assignment array is fill.

example for Category::class :

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
   /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['nom'];

}

You have to do the same for your other class mass assignment property. To get more information about read this . Good luck and happy coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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