Turning Custom Mysql Function Alias Into Model Variable

(Bill) #1

I’ve got the following table set up for a MANY::MANY relation:

category > category_listing > listing

I’ve create a custom MySQL function to speed up GeoIP calculations, which I’m calling using CDbExpression in a parameterized scope in the category_listing model and assigning the alias ‘distance’:

public function withinRadius($radius)





			'select'=>array(new CDbExpression("fn_distance_cosine({$user->lat},{$user->lng},listing.lat,listing.lng) as distance")),


			'order'=>'distance ASC',

			'condition'=>"listing.lat BETWEEN {$min_lat} AND {$max_lat} AND listing.lng BETWEEN {$min_lng} AND {$max_lng}",

			'having'=>"distance <= {$radius}",



		return $this;


I’ve defined distance as a variable within the category_listing model:

public $distance;

And now I can call the following:

$categoryListings = EldCategoryListing::model()->withinRadius(25)->findAllByAttributes(array('category_id'=>$id));

But the problem is, I can’t access $distance as a variable. $categoryListings[0]->distance is not set. I’ve also tried defining $distance as an attribute of listing, and calling $categoryListings[0]->listing->distance, and this doesn’t work.

What am I doing wrong?

(Alirz23) #2

I guess you have to use


to get hold of that property

(Bill) #3

Strangely, $categoryListings[0]->distance seems to be working now. I’m guessing there was some caching at play that was preventing my code updates from displaying.

Apologies for the false alarm.