public function saveCategories(array $categoriesId)
{
$categoriesId = array_diff($categoriesId, (array) $this->category_id);
$currentCategories = Yii::app()->getDb()->createCommand()->select('category_id')->from('{{store_product_category}}')->where('product_id = :id', [':id' => $this->id])->queryColumn();
if ($categoriesId == $currentCategories) {
return true;
}
$transaction = Yii::app()->getDb()->beginTransaction();
try {
Yii::app()->getDb()->createCommand()->delete('{{store_product_category}}', 'product_id = :id', [':id' => $this->id]);
if (!empty($categoriesId)) {
$data = [];
foreach ($categoriesId as $id) {
$data[] = ['product_id' => $this->id, 'category_id' => (int) $id];
}
Yii::app()->getDb()->getCommandBuilder()->createMultipleInsertCommand('{{store_product_category}}', $data)->execute();
}
$transaction->commit();
return true;
} catch (Exception $e) {
$transaction->rollback();
return false;
}
}