Accessing Database 'as' Value From Cactivedataprovider


I have the following model that serves to represent a store’s location, included in that location are it’s longitude and latitude. I want a user to be able to search by their location and be given a list of nearest stores and the distance they currently are from that location. I am able to return a list of nearest stores in sorted order from the following code, however, I do not know how to extract the ‘distance’ value that is set from the ‘AS’ MySQL query. Ideally I would return this calculated ‘distance’ as if it was a property of each model.

Is there a way to get ‘AS’ values from an SQL query within yii?

class Location extends CActiveRecord



   public function search()


      $criteria = new CDbCriteria;

      	// special calculation for distance

	if( isset( $this->latitude ) && isset( $this->longitude ) ){

		$criteria->params = array(

			':curr_lat' => $this->latitude,

			':curr_lon' => $this->longitude,


		// The Haversine Formula, used to calculate lat long distances from two locations

		$criteria->select = 



				3959 * acos( 

					cos( radians(:curr_lat) ) * 

					cos( radians( latitude ) ) * 

					cos( radians( longitude ) - radians(:curr_lon) ) + 

					sin( radians(:curr_lat) ) * 

					sin( radians( latitude ) ) 


			) AS distance    // this is the value I would like to return with the found models


		$criteria->order = '`distance` ASC';


	$criteria->limit = 10;

	return new CActiveDataProvider($this, array(






Any suggestions?


I think that you just need to define a public attribute in your class to hold the value.

Try putting this at the top of your class:

class Location extends CActiveRecord


    public $distance;




Thanks for the quick tip. I added the public attribute, however, the distance attribute was set to null for all the models retrieved by


Any other advice?