简体   繁体   中英

php artisan db:seed using laravel error when creating Faker for table that have foreign keys

database/migrations/2018_12_20_022430_create_products_table.php

> class CreateProductsTable extends Migration {
>     /**
>      * Run the migrations.
>      *
>      * @return void
>      */
>     public function up()
>     {
>         Schema::create('products', function (Blueprint $table) {
>             $table->increments('id');
>             $table->string ('name');
>             $table->text('description');
>             $table->decimal('price');
>             $table->string('file');
>             $table->timestamps();
>         });
>     }

database/migrations/2018_12_20_042857_create_cards_table.php

class CreateCardsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('cards', function (Blueprint $table) {
            $table->increments('id');
            $table->string ('quantity');
            $table->string('status');
            $table->integer('pid')->unsigned();
            $table->foreign('pid')->references('id')->on('products');
            $table->integer('cid')->unsigned();
            $table->foreign('cid')->references('id')->on('customers');

            $table->timestamps();
        });
    }

database/factories/UserFactory.php

$factory->define(App\Product::class, function (Faker $faker) { 
    return [
              //'id'=>$faker->numberBetween($min = 1, $max = 20),
              'name'=> $faker->word,
              'description'=> $faker->sentence($nbWords = 6, $variableNbWords = true),
              'price' => $faker->randomFloat($nbMaxDecimals = 100, $min = 1, $max = 10),
              'file' => $faker->imageUrl($width = 640, $height = 480),
    ];
});


$factory->define(App\Card::class, function (Faker $faker) {
    return [
               //'id'=>$faker->numberBetween($min = 1, $max = 20),
               'quantity'=>$faker->sentence($nbWords = 6, $variableNbWords = true),
               'status'=>$faker->boolean($chanceOfGettingTrue = 10),
               'cid'=>$faker->numberBetween($min = 1, $max = 20),
              'pid'=>$faker->numberBetween($min = 1, $max = 20),
    ];
});

routes/web.php

factory(App\Product::class,5)->create();
factory(App\Card::class,5)->create();

Terminal:

$ php artisan db:seed

Error :

In Connection.php line 664: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ( food . cards , CONSTRAINT ca rds_pid_foreign FOREIGN KEY ( pid ) REFERENCES products ( id )) (SQL: in sert into cards ( quantity , status , cid , pid , updated_at , creat ed_at ) values (Vitae asperiores eligendi ipsam exercitationem quidem., 1,
18, 8, 2019-01-02 04:22:10, 2019-01-02 04:22:10))

In Connection.php line 458: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ( food . cards , CONSTRAINT ca rds_pid_foreign FOREIGN KEY ( pid ) REFERENCES products ( id ))

You have to use ID of a product and a customer instead of random number:

$factory->define(App\Card::class, function (Faker $faker) {
    $p_ids = App\Product::pluck('id')->toArray();
    $c_ids = App\Customer::pluck('id')->toArray();
    return [
               //'id'=>$faker->numberBetween($min = 1, $max = 20),
               'quantity'=>$faker->sentence($nbWords = 6, $variableNbWords = true),
               'status'=>$faker->boolean($chanceOfGettingTrue = 10),
               'cid'=>$faker->randomElement($c_ids),
               'pid'=> $faker->randomElement($p_ids),
    ];
});

in short, select all ids from products and customers tables, and take a random value from them to use it as foreign key.

but make sure your factories are in specific order, so CardFactory must be fired after ProductFactory and CustomerFactory .

if pid has random values but the database will not enter a value to pid in the cards table that does not exist in the products table . the value that is inserted in pid must exist in product id .

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