deleteAll applying scope criteria not working correctly

Hey!
So, i know that by design, Yii’s deleteAll() does not take scopes by design, and while i found a “workaround” (Using updateAll and deleteAll with scopes | Wiki | Yii PHP Framework), its still not behaving correctly.
Basically, i have a scope which refers a column (in this case, user_idx) in a table named tbl_clients, so, i call it via a scope funcion to look at clients.user_idx, however, when applying that to the workaround, it tries to look for a column named clients.user_idx in my main table, which is, incorrect.

How can i make it so that workaround correctly applies the scope? Or is there any way to reach the same result without using scopes?

The error in question Column not found: 1054 Unknown column 'client.user_idx' in 'where clause'. The SQL statement executed was: DELETE FROM tbl_rules_cash_relation WHERE (client.user_idx=:user_distributor_idx) AND (rule_idx=:rule_idx)

The code:

In Controller file: 
MyModel:model()->user(Yii::app()->user->idx)->rule($rule_idx)->deleteAllWithinScope();

In Model file:
public function user_client($client_idx) {
        $this->getDbCriteria()->mergeWith(array(
            'with' => array('store', 'store.client'),
            'condition' => 'client.client_idx=:user_client_idx',
            'params' => array(':user_client_idx'=> $client_idx)
        ));
        return $this;
    }

The deleteAllWithinScope() function does the same as the wiki code.

This happens because deleteAll() in Yii 1.x does not support JOINs or relational scopes (with). So when your scope adds with => store.client, Yii ignores the JOIN but still keeps the condition, causing the error (client.user_idx not found).

Solutions:

1) Use subquery (recommended)
Instead of relying on with, filter using a subquery:

MyModel::model()->deleteAll(
    'rule_idx = :rule_idx AND store_id IN (
        SELECT s.id FROM store s
        JOIN client c ON c.client_idx = s.client_idx
        WHERE c.user_idx = :user_idx
    )',
    [
        ':rule_idx' => $rule_idx,
        ':user_idx' => Yii::app()->user->idx,
    ]
);

2) Fetch IDs first, then delete

$models = MyModel::model()
    ->with('store.client')
    ->findAll('client.user_idx = :uid AND rule_idx = :rid', [
        ':uid' => Yii::app()->user->idx,
        ':rid' => $rule_idx,
    ]);

$ids = array_map(fn($m) => $m->id, $models);

MyModel::model()->deleteByPk($ids);

3) Raw SQL (fastest for large data)
Use Yii::app()->db->createCommand() with JOIN delete.


Key Point

Scopes with with work for SELECT, not for DELETE/UPDATE in Yii 1.x. You must:

  • Use subqueries, or
  • Pre-fetch IDs

If you want, I can convert your exact scope into a clean reusable function
Email: a03003132335@gmail.com
WhatsApp: +923133473749