K
K
Konstantin T2015-06-16 21:46:16
MySQL
Konstantin T, 2015-06-16 21:46:16

Why might count in a model not work correctly in Yii?

I make a simple request:

$criteria = new CDbCriteria();
$criteria->addCondition('t.user_id = :uid OR company.id IN (:cid)');
$criteria->with = array('company' => array('select' => 'Name'));
$criteria->params = array(':uid' => Yii::app()->user->id, ':cid' => implode(', ', $arCID));
Bill::model()->count($criteria)

From which it turns out:
SELECT COUNT(DISTINCT `t`.`id`) FROM `o_bills` `t` LEFT OUTER JOIN `o_company` `company` ON (`t`.`companyId`=`company`.`id`) WHERE (t.user_id = :uid OR company.id IN (:cid))

and this code returns 10 positions
Made the same query directly to the database, got 25 records. I thought that maybe I'm working directly with another database (copy), for the test I added a record to the database, I got 11 from Yii and 26 from the muscle directly, deleted 3 records -> Yii = 10 , Mysql = 23 .
There are no default expressions in the model that could attach to the request and affect the result, but just in case, I got into the code in the very place where the request goes to the database ( Github per line ) displays the same value! What could it be?
Solution:
I rewrote the query like this, in fact the same SQL is obtained, but it works correctly. What is the catch and did not understand!
$criteria = new CDbCriteria();
$criteria->addInCondition('company.id', $arCID);
$criteria->addCondition('t.user_id = :uid', 'OR')->params[':uid'] = Yii::app()->user->id;
$criteria->with = array('company' => array('select' => 'Name'));

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Makarov, 2015-06-17
@RooTooZ

Yii does not count the number of raw rows returned, but the number of Bill models returned.

E
Evgeny Lebedev, 2015-06-16
@HollowJ

as an option, not all records in the database have fields filled in, which are indicated as mandatory in the model. In this case, the framework will ignore them, as far as I remember.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question