Код: Выделить всё
/**
* @param $relations массив ($relation => $exclude), где $exclude - массив id объектов связи с которыми разрывать не нужно
* @return bool
*/
public function clear($relations)
{
$commands = array();
foreach ($relations as $relation => $exclude)
{
list($table, $fk1, $fk2) = $this->parseManyMany($relation);
$criteria = new CDbCriteria(array(
'condition' => $fk1.'='.$this->owner->id,
));
$criteria->addNotInCondition($fk2, $exclude);
$commands[] = Yii::app()->db
->getCommandBuilder()
->createDeleteCommand($table, $criteria);
}
return $this->execInTransaction($commands);
}
public function execInTransaction($commands)
{
$flag = $transaction = Yii::app()->db->getCurrentTransaction();
if ($transaction === null)
{
$transaction = Yii::app()->db->beginTransaction();
}
try
{
foreach ($commands as $c)
{
$c->execute();
}
//no commit, because withRelated save
} catch (CException $e)
{
if ($flag !== null)
{
$transaction->rollback();
return false;
}
}
return true;
}
public function parseManyMany($relation)
{
preg_match('/^\s*(.*?)\((.*)\)\s*$/', $this->owner->getMetaData()->relations[$relation]->foreignKey, $matches);
$fks = preg_split('/\s*,\s*/', $matches[2], -1, PREG_SPLIT_NO_EMPTY);
return array(
$matches[1],
$fks[0],
$fks[1]
);
}
Код: Выделить всё
$this->withRelated->clear(array(
'categories' => $this->has_category,
'relevant_products' => $this->relevant_products_arr
));