Mr.Json
Mr.Json

Reputation: 149

Pivot table attach() without auto sort

$item->categories()->attach([4,1,2,3]);

This code inserts record order by 1 2 3 4

enter image description here I want it to insert exactly like array order!! 4 1 2 3 How I do it?

"laravel/framework": "5.5.*",

I Add timestamps to it, but again not work.

enter image description here

Item.php

public function categories()
{
        return $this->belongsToMany('App\Category')->withTimestamps();
}

Category.php

public function items()
{
        return $this->belongsToMany('App\Item');
}

Pivot migration:

public function up()
{
        Schema::create('category_item', function (Blueprint $table) {

            $table->integer('item_id')->unsigned()->index();
            $table->foreign('item_id')->references('id')->on('items')->onDelete('cascade');

            $table->integer('category_id')->unsigned()->index();

            $table->foreign('category_id')->references('id')
                        ->on('categories')->onDelete('restrict');

            $table->primary(['item_id', 'category_id']);

            $table->timestamps(); 

        });
}

Upvotes: 1

Views: 81

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

The attach() method respect the given order (Tested), but the order you see in your PHPMyAdmin panel is the auto order when there's no primary key to order with.

Since the data will be patched at the same time to your DB you can't get the ordered list without using primary key id in the pivot table.

NOTE: You may need to use the sync method in this case, It will simplify the edit mode.

Upvotes: 1

Adrian Hernandez-Lopez
Adrian Hernandez-Lopez

Reputation: 553

Add a primary key and use sync() to save the data instead of attach, unless you want to keep adding entries. Here is the migration updated:

public function up()
{
    Schema::create('category_item', function (Blueprint $table) {

        $table->increments('id');

        $table->integer('item_id')->unsigned()->index();
        $table->foreign('item_id')->references('id')->on('items')->onDelete('cascade');

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

        $table->unique(['item_id', 'category_id'], 'item_category_unique');

        $table->timestamps(); 

    });

}

Upvotes: 1

Related Questions