Active record question model()->findAll()

Is it possible to make model()->findAll() to return an additional field distance that is calculating? Looks like it returns only db fields.




//User model

...

public static function searchUsers($latitude = null, $longitude = null)

  {

   $criteria = new CDbCriteria;

   $criteria->select = 'id,

                        email,

                        name,

( 3959 * acos( cos( radians(' . $latitude . ') ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(' . $longitude . ') ) + sin( radians(' . $latitude . ') ) * sin( radians( lat ) ) ) ) * 1.609344 AS distance';


   $criteria->having = 'distance < ' . Yii::app()->params['searchDistance'];

   $criteria->order = 'distance ASC';

   $rows = self::model()->findAll($criteria);

   return $rows;

 }

This code works properly, but doesn’t return distance field in the results.

When searching the forum, remember to repeat the search since there is still a intermittent problem with forum search.

You can find the answer to your question here.

/Tommy

Yes, it becomes accessible when you do the next:


foreach($users as $user){

    echo $user->distance;

}

But there is another question. After selecting data I put it in array and then send it using JSON:




$this->_response['users'] = $users;

$this->respond( $this->_response );


header("Content-Type: text/{$_contentType}; charset=UTF-8");

echo CJSON::encode($response);

Yii::app()->end();



And in the response this field is absent.

I think some method __toString() called when JSON::encode() runs. And this method doesn’t include distance property.

Maybe you know some good fix for that?

Ok. Solved it with additional foreach.

OK, I’m prett new to yii… but y not do the following? i.e. remove the whole calculation out of the sql syntax and create it as a separate new variable?





$distant_variable = ( ( 3959 * acos( cos( radians(' . $latitude . ') ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(' . $longitude . ') ) + sin( radians(' . $latitude . ') ) * sin( radians( lat ) ) ) ) * 1.609344);




public static function searchUsers($latitude = null, $longitude = null)

  {

   $criteria = new CDbCriteria;

   $criteria->select = 'id,

                        email,

                        name,

			$distant_variable  AS distance';


   $criteria->having = 'distance < ' . Yii::app()->params['searchDistance'];

   $criteria->order = 'distance ASC';

   $rows = self::model()->findAll($criteria);

   return $rows;

 }




[color="#2B3730"][b]

[/b][/color]

[color="#2B3730"][b]

[/b][/color]

[color="#2B3730"]i think both approach is enough for desired query.[/color]

[color="#2b3730"]but which one is take place AS fast executioner. [/color]

[color="#2B3730"][b]

[/b][/color]