diff --git a/framework/db/BaseActiveRecord.php b/framework/db/BaseActiveRecord.php
index f4b7909..cc2f9dc 100644
--- a/framework/db/BaseActiveRecord.php
+++ b/framework/db/BaseActiveRecord.php
@@ -1297,8 +1297,6 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
     public function unlinkAll($name, $delete = false)
     {
         $relation = $this->getRelation($name);
-        /** @var Command $command */
-        $command = static::getDb()->createCommand();
         $columns = [];
         $condition = [];
         if (empty($relation->via)) {
@@ -1308,18 +1306,22 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
                 foreach ($relation->link as $a => $b) {
                     $condition[$a] = $this->$b;
                 }
-                $command->delete($viaClass::tableName(), $condition)->execute();
+                $viaClass::deleteAll($condition);
             } else {
                 foreach ($relation->link as $a => $b) {
                     $columns[$a] = null;
                     $condition[$a] = $this->$b;
                 }
-                $command->update($viaClass::tableName(), $columns, $condition)->execute();
+                $viaClass::updateAll($columns, $condition);
             }
         } else {
-            $viaTable = $viaTable = reset($relation->via->from);
+            $viaTable = reset($relation->via->from);
+
             /** @var ActiveQuery $viaRelation */
             $viaRelation = $relation->via;
+
+            /** @var Command $command */
+            $command = static::getDb()->createCommand();
             if ($delete) {
                 foreach ($viaRelation->link as $a => $b) {
                     $condition[$a] = $this->$b;
diff --git a/tests/unit/framework/ar/ActiveRecordTestTrait.php b/tests/unit/framework/ar/ActiveRecordTestTrait.php
index a8960b4..840860f 100644
--- a/tests/unit/framework/ar/ActiveRecordTestTrait.php
+++ b/tests/unit/framework/ar/ActiveRecordTestTrait.php
@@ -45,6 +45,10 @@ trait ActiveRecordTestTrait
      */
     abstract public function getItemClass();
 
+    abstract public function getOrderWithNullFKClass();
+
+    abstract public function getOrderItemWithNullFKmClass();
+
     /**
      * can be overridden to do things after save()
      */
@@ -724,7 +728,7 @@ trait ActiveRecordTestTrait
 
     public function testUnlinkAll()
     {
-        /** @var \yii\db\ActiveRecordInterface $customerClass */
+        /** @var \yii\db\ActiveRecordInterface $customewdfsdfdfsfd
         $customerClass = $this->getCustomerClass();
         /** @var \yii\db\ActiveRecordInterface $orderClass */
         $orderClass = $this->getOrderClass();