E
E
evilelf2015-03-20 16:28:23
Yii
evilelf, 2015-03-20 16:28:23

How to find the number of changed lines in yii?

Have a great Friday day!)
I've been working with yii for the second month, I really like it) I ran
into a problem in working with yii.
Who, how solved the problem?)
Here is a piece of code:

$sql = "INSERT INTO  {{".$table."}} ( ".$arrKey['KEY'].", ". implode(', ', $column) ." ) VALUES ".implode(',',$question_marks)." ON DUPLICATE KEY UPDATE meta_val = VALUES(meta_val);";
$command=Yii::app()->db->createCommand($sql);
$res=$command->execute();

in $res I return "0" if the cells have been updated. But if the rows were added, then 1 is returned.
How to find out the number of affected rows?
Thanks!)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
Hesed, 2015-03-28
@Hesed

The "on duplicate key update" criterion is only in MySQL (and forks) and is not very good to use, as well as to hardcode the SQL query when there is DAO/AR. Essentially, "on duplicate key update" according to the official documentation returns 1 if the row was inserted and 2 if it was updated. Since this is the behavior of MySQL itself, there is no way around this with Yii.
To solve the problem, I would reconsider the expression itself and the approach to writing queries. For example:

// Ищем, существует ли запись с ключом $id
$model = MetaModel::model()->findByPk($id);

// Если записи нет, мы будем делать insert
if(!$model) {
    $model = new MetaModel();
    // Присваиваем атрибуты. Позаботьтесь о том, чтобы массив $attrs содержал их
    $model->attributes = $attrs;
    $res = $model->save();
}
else {
    $res = Yii::app()->db->createCommand()
        ->update('{{table}}',        // название таблицы
            array(
                'meta_val'=>':meta', // какое поле
            ), 
            'id=:id',                // where id = ...
            array(
                ':id' => $id,        // param binding
                ':meta' => 'blablabla'
            )
        )
        ->execute();
}

echo intval($res).' rows affected';

The code is blindly written and not tested. It definitely needs to be sharpened to fit your needs, I just offer my own version. More cumbersome? Yes, but we
PS This is a head-on solution that requires minimal changes to the existing code. In a good way, of course, such tasks should be solved before the request at the script level. Or hang behavior.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question