我想按数组顺序存储ID
$item->categories()->attach(request('category_ids'));
例如:
如果request('category_ids')
等于:[4,3,2,1]
我要按顺序存储记录=> 4 3 2 1
我的数据透视表:
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']);
});
我在laravel上打开了一个issues。
答案 0 :(得分:0)
我认为您需要覆盖attach方法,但是
我想与订单一起显示给我的客户。还有另一种方法吗? –杰森先生
您可以这样做:
Item::with(['categories' => function ($query) {
$query->orderBy('category_id', 'desc');
}])->all();
发表评论后,我认为您需要在sort
表中的category_item
列:
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('sort')->unsigned()->nullable(false);
$table->integer('category_id')->unsigned()->index();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('restrict');
$table->primary(['item_id', 'category_id']);
});
现在,需要您的地图请求,例如:
$categoryIds = array_map(function ($categoryId) {
return ['category_id' => $categoryId, 'sort' => $categoryId];
}, request('category_ids'))
并附加:
$item->categories()->attach($categoryIds);