public function unlinkAll($name, $delete = false)
{
$relation = $this->getRelation($name);
if ($relation->via !== null) {
if (is_array($relation->via)) {
list($viaName, $viaRelation) = $relation->via;
$viaClass = $viaRelation->modelClass;
unset($this->_related[$viaName]);
} else {
$viaRelation = $relation->via;
$viaTable = reset($relation->via->from);
}
$condition = [];
$nulls = [];
foreach ($viaRelation->link as $a => $b) {
$nulls[$a] = null;
$condition[$a] = $this->$b;
}
if (!empty($viaRelation->where)) {
$condition = ['and', $condition, $viaRelation->where];
}
if (property_exists($viaRelation, 'on') && !empty($viaRelation->on)) {
$condition = ['and', $condition, $viaRelation->on];
}
if (is_array($relation->via)) {
if ($delete) {
$viaClass::deleteAll($condition);
} else {
$viaClass::updateAll($nulls, $condition);
}
} else {
$command = static::getDb()->createCommand();
if ($delete) {
$command->delete($viaTable, $condition)->execute();
} else {
$command->update($viaTable, $nulls, $condition)->execute();
}
}
} else {
$relatedModel = $relation->modelClass;
if (!$delete && count($relation->link) === 1 && is_array($this->{$b = reset($relation->link)})) {
$this->$b = [];
$this->save(false);
} else {
$nulls = [];
$condition = [];
foreach ($relation->link as $a => $b) {
$nulls[$a] = null;
$condition[$a] = $this->$b;
}
if (!empty($relation->where)) {
$condition = ['and', $condition, $relation->where];
}
if (property_exists($relation, 'on') && !empty($relation->on)) {
$condition = ['and', $condition, $relation->on];
}
if ($delete) {
$relatedModel::deleteAll($condition);
} else {
$relatedModel::updateAll($nulls, $condition);
}
}
}
unset($this->_related[$name]);
}
關於
save()
方法,$attributeNames
描述的註解。它說:「需要儲存的屬性名稱列表。預設為 null,表示將儲存從 DB 載入的所有屬性。」
這並非 100% 正確,因為 Yii 2 僅儲存髒屬性 (https://yii.dev.org.tw/doc/guide/2.0/en/db-active-record#dirty-attributes)。
(順帶一提,這是 Yii 1 的巨大改進!)
API 文件有些問題
> EVENT_AFTER_FIND yii\db\Event
但命名空間 yii\db 中不存在類別 Event - 且看起來應該是 yii\base\ModelEvent
為了發表評論,請註冊或登入。