Множественная вставка в pivot таблицу
Подскажите, как делать множественную вставку в pivot-таблицу?
Есть две таблицы: categories, attributes
и связывающая таблица attribute_category
Schema::create('attribute_category', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('attribute_id');
$table->unsignedBigInteger('category_id');
$table->foreign('category_id')->references('id')->on('categories')
->onDelete('cascade')
->onUpdate('cascade');
$table->foreign('attribute_id')->references('id')->on('attributes')
->onDelete('cascade')
->onUpdate('cascade');
});
App\Models\Category
class Category extends Model {
public function attribute(){
return $this->belongsToMany('App\Models\Attribute');
}
}
App\Models\Attribute
class Attribute extends Model {
public function category(){
return $this->belongsToMany('App\Models\Category');
}
}
controller
$attributes = ['attrib1','attrib2','attrib3'];
Category::get()->each(function($category) use($attributes){
Attribute::whereIn('name', $attributes)->each(function($attribute) use($category){
$category->attribute()->attach($attribute);
});
});
В результате получаются примерно такие запросы:
"insert into `attribute_category` (`attribute_id`, `category_id`) values (?, ?)"
"insert into `attribute_category` (`attribute_id`, `category_id`) values (?, ?)"
"insert into `attribute_category` (`attribute_id`, `category_id`) values (?, ?)"
"select * from `attributes` where `name` in (?, ?, ?) order by `attributes`.`id` asc limit 1000 offset 0"
"insert into `attribute_category` (`attribute_id`, `category_id`) values (?, ?)"
"insert into `attribute_category` (`attribute_id`, `category_id`) values (?, ?)"
"insert into `attribute_category` (`attribute_id`, `category_id`) values (?, ?)"
"select * from `attributes` where `name` in (?, ?, ?) order by `attributes`.`id` asc limit 1000 offset 0"
"insert into `attribute_category` (`attribute_id`, `category_id`) values (?, ?)"
"insert into `attribute_category` (`attribute_id`, `category_id`) values (?, ?)"
"insert into `attribute_category` (`attribute_id`, `category_id`) values (?, ?)"
Как можно сократить запросы?