Take the 2-minute tour ×

I am working in Yii and, I have a table named : visits

It has two foreign keys : from_user_id and to_user_id which are linked to the 'user' table. Now the table visits has many same 'from_user_id' and I want to get retrieve them in Yii as DISCTINCT.

This is my code :

$visited = Visit::model()->findAllByAttributes(array('to_user_id'=>Yii::app()->user->id));

$criteria = new CDbCriteria();
$criteria->distinct = true;

foreach($visited as $visits){

    echo User::model()->findByPk($visits->from_user_id,$criteria)->getFullName($visits->from_user_id);

   echo " <br>";

However, I am not able to get them as distinct.

This is my output :


I want the output as :


This is not getting me distinct values. Where am I going wrong??

share|improve this question
But what other columns are being returned ? print_r($visits) in the loop. Just because the value of from_user_id isn't distinct alone in that query doesn't mean it is not part of a larger distinct dataset. –  Michael Berkowski Aug 3 '13 at 10:48
I'm not familiar enough with the Yii framework to know what the method is for retrieving only one column in a query. –  Michael Berkowski Aug 3 '13 at 10:50
MichaelBerkowski is correct, you need to tell Yii to select only the from_user_id column. This is done by $criteria->select = 'from_user_id'; 2. Since you have foreign keys, you should also have corresponding relations. Tell Yii to eager load the relation that corresponds to the from_user_id foreign key, and get all your data in one query instead of N+1. –  DCoder Aug 3 '13 at 11:17
Thank you @DCoder!! I was missing the 'select' criteria only. –  Sankalp Singha Aug 3 '13 at 11:32
add comment

1 Answer

I wasn't be able to test it, but apart from possible minor syntax adjustment, this should help you:

    array('distinct' => True)

According to the doc, findAllByAttribute accept a condition or criteria parameter as second argument.

If this is an array (according the doc for find()), it will serve to initialize the various criteria properties of the requests.

share|improve this answer
That still does a SELECT DISTINCT * FROM visits WHERE to_user_id = :to_user_id. –  DCoder Aug 3 '13 at 11:15
@DCoder : Exactly! And Thanks to you , I was able to do it... It was missing :) Thank you!! –  Sankalp Singha Aug 3 '13 at 11:32
add comment

Your Answer


