public function unlinkAll(string $relationName, bool $delete = false): void
{
$viaModel = null;
$viaTable = null;
$relation = $this->relationQuery($relationName);
$viaRelation = $relation->getVia();
if ($viaRelation !== null) {
if (is_array($viaRelation)) {
[$viaName, $viaRelation] = $viaRelation;
$viaModel = $viaRelation->getModel();
unset($this->related[$viaName]);
} else {
$from = $viaRelation->getFrom();
$viaTable = reset($from);
}
$condition = [];
$nulls = [];
if ($viaRelation instanceof ActiveQueryInterface) {
foreach ($viaRelation->getLink() as $a => $b) {
$nulls[$a] = null;
$condition[$a] = $this->get($b);
}
if (!empty($viaRelation->getWhere())) {
$condition = ['and', $condition, $viaRelation->getWhere()];
}
if (!empty($viaRelation->getOn())) {
$condition = ['and', $condition, $viaRelation->getOn()];
}
}
if ($viaModel !== null) {
if ($delete) {
$viaModel->deleteAll($condition);
} else {
$viaModel->updateAll($nulls, $condition);
}
} elseif (is_string($viaTable)) {
$command = $this->db()->createCommand();
if ($delete) {
$command->delete($viaTable, $condition)->execute();
} else {
$command->update($viaTable, $nulls, $condition)->execute();
}
}
} else {
$relatedModel = $relation->getModel();
$link = $relation->getLink();
if (!$delete && count($link) === 1 && is_array($this->get($b = reset($link)))) {
$this->set($b, []);
$this->save();
} else {
$nulls = [];
$condition = [];
foreach ($relation->getLink() as $a => $b) {
$nulls[$a] = null;
$condition[$a] = $this->get($b);
}
if (!empty($relation->getWhere())) {
$condition = ['and', $condition, $relation->getWhere()];
}
if (!empty($relation->getOn())) {
$condition = ['and', $condition, $relation->getOn()];
}
if ($delete) {
$relatedModel->deleteAll($condition);
} else {
$relatedModel->updateAll($nulls, $condition);
}
}
}
unset($this->related[$relationName]);
}
Signup or Login in order to comment.