A
A
Alexey Nikolaev2015-10-06 20:45:32
MySQL
Alexey Nikolaev, 2015-10-06 20:45:32

How to use mysql functions in ActiveRecord when searching for a record?

Good evening everyone.
I am looking for a user by his unique token. In a normal request, everything looks like this:

SELECT login FROM `users` WHERE MD5(CONCAT(`users`.`id`,  Yii::app()->params->salt )) = $token

It works, but when I try to use ActiveRecord and CDbCriteria I get an error. I do like this:
$criteria=new CDbCriteria;
$criteria->select='login';
$criteria->condition = 'hash=:hash';
$criteria->params = [
      ':hash' => "MD5(CONCAT(`users`.`id`, '" . Yii::app()->params->salt . "'))"
];
$arUser = (new User)->find($criteria);

But it doesn't work, because passing strings with functions to the parameters in this way, as expected, gives an error about an incorrect sql query. I found options using CDbExpression or findBySql, but this kills all the beauty of working through AR. How to be?
Thanks in advance for your advice.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Pavlenko, 2015-10-06
@Akdmeh

Alas, it is necessary to use CDbExpression. Yes, compatibility between databases is being killed, but what can you do.

B
bashkarev, 2015-10-06
@bashkarev

Try adding a scope to the model

public function scopes()
    {
        return [
            'hash'=>[
                'condition'=>"hash=MD5(CONCAT(`users`.`id`, '" . Yii::app()->params->salt . "'))"
            ]
        ];
    }

and chooseUser::model()->hash()->find();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question