samedi 11 août 2018

PDOException::("SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'Laptop1' for key 'products_name_unique'")

This is My ProductsTableSeeder I create the products into products table and relationship with cateogries creating category_product table and adding foreign key to that.

I have an error when I migrate and seed the data it says duplicate. How do I fix it?

use App\Product;
use Illuminate\Database\Seeder;

class ProductsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //

        //Product::truncate();

        for($i = 1; $i <= 10; $i++){
            Product::updateOrCreate([
                'name'=> 'Laptop'.$i,
                'slug' => 'laptop'.$i,
                'details' => [13,14,15][array_rand([13,14,15])].'inch,'.[1,2,3][array_rand([1,2,3])].'TB SSD,32GB RAM',
                'price' => rand(1500,3000),
                'description' => 'Lorem'.$i.' ipsum dolor sit amet, consectetur adipiscing elit. Maecenas fermentum. laoreet turpis, nec sollicitudin dolor cursus at. Maecenas aliquet, dolor a faucibus efficitur, nisi tellus cursus urna, eget dictum lacus turpis.',
                ])->categories()->attach(1);
        }
        $product = Product::find(1)-> categories()->attach(2); 
}

This is Product Table.

  public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->string('slug')->unique();
            $table->string('details')->nullable();
            $table->float('price');
            $table->text('description');
            //$table->integer('category_id');
            $table->timestamps();
        });
    }

This is Category Table.

public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->string('slug')->unique();
            $table->timestamps();
        });
    }

This is relationship table.

public function up()
    {
        Schema::create('category_product', function (Blueprint $table) {
            $table->increments('id');

            $table->integer('product_id')->unsigned()->nullable();
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');

            $table->integer('category_id')->unsigned()->nullable();
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');

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




Aucun commentaire:

Enregistrer un commentaire