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

1828 views php
0

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))

answered question

You can't use random number as pid as it is expecting a foreign key that exists on Product table at id column.

so how can i relate pid to it's origin table?

2 Answers

1

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.

posted this
5

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.

posted this

Have an answer?

JD

Please login first before posting an answer.