How To Return Empty Result In Has_One Relationship

Hi Guys - I am having below relationship in my Model:


'userAverageTime' => array(self::HAS_ONE, 'UserStatistics', 'user_id','condition'=>"userAverageTime.key='AVERAGE_TIME'")

It is working perfectly fine if we are having result for a particular user in “UserStatistics” table. But if we don’t have any result in userStatistics table for any user than no result for that user is being shown. I just want an option to show results with blank userStatistics object or without userStatistics object. But it is making an INNER JOIN for userStatistics object. I have tried below options also:

Below options are not working for me:




'userAverageTime' => array(self::HAS_ONE, 'UserStatistics', 'user_id','condition'=>"userAverageTime.key='AVERAGE_TIME'",'joinType'=>'LEFT OUTER JOIN'),




'userAverageTime' => array(self::HAS_MANY, 'UserStatistics', 'user_id','condition'=>"userAverageTime.key='AVERAGE_TIME'"),





'userAverageTime' => array(self::HAS_MANY, 'UserStatistics', 'user_id','condition'=>"userAverageTime.key='AVERAGE_TIME'",'joinType'=>'LEFT OUTER JOIN'),



Can anyone suggest something?

Thanks,

Ravi Verma




$stats = $user->userAverageTime;

if( $stats === null ) {

  $stats = new UserStatistics();

}

...



this should do the trick.

Hi RedGuy: Thanks for your reply. Actually I’m using this relationship in Query. So my query is not returning me all those users which are not having any data in UserStatistics Table. I can use above trick but in that case, I need to loop all the results and check if they are having any data in userStatistics or not. That would not be good idea for large data sets.

Can u please suggest something else?

Thanks,




$results = User::model()->with( 'userAverageTime' )->findAll( array(

  'condition'=>'userAverageTime.user_id IS NULL'

) );



is that what you want? relations are by default joined with ‘OUTER JOIN’ so when related record does not exists - there will be null value.