无需自动排序的数据透视表attach()

时间:2018-08-10 08:50:21

标签: laravel eloquent

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

此代码按1 2 3 4插入记录顺序

enter image description here 我希望它完全像数组顺序一样插入!! 4 1 2 3 我该怎么做?

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

我在上面添加了时间戳,但再次无法正常工作。

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');
}

数据透视迁移:

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

        });
}

2 个答案:

答案 0 :(得分:1)

attach()方法遵循给定的顺序(“已测试”),但是当您没有要使用的主键进行排序时,您在PHPMyAdmin面板中看到的顺序就是自动顺序。

由于数据将同时修补到您的数据库,因此如果不使用数据透视表中的主键id,就无法获得有序列表。

注意:在这种情况下,您可能需要使用sync方法,它将简化编辑模式。

答案 1 :(得分:1)

添加一个主键,并使用sync()保存数据而不是附加数据,除非您想继续添加条目。这是更新的迁移:

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

    });

}