#116674 Исследование путей решения проблем дублирования записей в таблицах price, price_value, supply, rest_item

This commit is contained in:
Александр Рыбкин 2025-09-01 16:14:41 +03:00
parent 12b888a674
commit 8ad15b4729
1 changed files with 85 additions and 0 deletions

View File

@ -2,6 +2,8 @@
namespace dominion\db;
use Yii;
/**
*
*/
@ -33,4 +35,87 @@ class ActiveRecord extends \yii\db\ActiveRecord
{
}
public function insertUpdate($runValidation = true, $attributes = null)
{
if ($runValidation && !$this->validate($attributes)) {
Yii::info('Model not inserted due to validation error.', __METHOD__);
return false;
}
if (!$this->isTransactional(self::OP_INSERT)) {
return $this->insertUpdateInternal($attributes);
}
$transaction = static::getDb()->beginTransaction();
try {
$result = $this->insertUpdateInternal($attributes);
if ($result === false) {
$transaction->rollBack();
} else {
$transaction->commit();
}
return $result;
} catch (\Exception $e) {
$transaction->rollBack();
throw $e;
} catch (\Throwable $e) {
$transaction->rollBack();
throw $e;
}
}
protected function insertUpdateInternal($attributes = null)
{
if (!$this->beforeSave(true)) {
return false;
}
$values = $this->getDirtyAttributes($attributes);
if (($primaryKeys = $this->schemaInsertUpdate(static::tableName(), $values)) === false) {
return false;
}
foreach ($primaryKeys as $name => $value) {
$id = static::getTableSchema()->columns[$name]->phpTypecast($value);
$this->setAttribute($name, $id);
$values[$name] = $id;
}
$changedAttributes = array_fill_keys(array_keys($values), null);
$this->setOldAttributes($values);
$this->afterSave(true, $changedAttributes);
return true;
}
public function schemaInsertUpdate($table, $columns)
{
$db = static::getDb();
foreach ($this->attributes() as $itemColumn) {
$column = $db->getSchema()->quoteColumnName($itemColumn);
$onDuplicateKeyValues[] = $column . ' = VALUES(' . $column . ')';
}
$command = $db->createCommand()->insert($table, $columns);
$sql = $command->getRawSql();
$sql .= ' ON DUPLICATE KEY UPDATE ' . implode(', ', $onDuplicateKeyValues);;
if (!$db->createCommand($sql)->execute()) {
return false;
}
$tableSchema = $this->getTableSchema($table);
$result = [];
foreach ($tableSchema->primaryKey as $name) {
if ($tableSchema->columns[$name]->autoIncrement) {
$result[$name] = $this->getLastInsertID($tableSchema->sequenceName);
break;
}
$result[$name] = isset($columns[$name]) ? $columns[$name] : $tableSchema->columns[$name]->defaultValue;
}
return $result;
}
}