Calculated Fields in AR

Hi all!

I have this query




       (hotel.rate_min / currency.value) AS rate_euros

FROM hotel

     INNER JOIN city ON ( = hotel.city_id)

     INNER JOIN country ON ( = city.country_id)

     INNER JOIN currency ON ( = country.currency_id)

WHERE hotel.feat_date >= NOW()


Can I have this part “(hotel.rate_min / currency.value) AS rate_euros” returned when I do ???

$criteria = new CDbCriteria( );

		$criteria->select = array(






		$criteria->condition = 'feat_date >= NOW()';

return $this->with( array(

			'city' => array(

				'select' => ','), 

			'country.currency' => array(

				'select' => 'value'), 

			'hotel_images' => array(

				'select' => '', 

				'group' => 'hotel_id')) )->findAll( $criteria );

Of course I can get all the fields from the tables and then calculate, but the point is that I want to order by that value.


I believe this could work:

//return $this->with( array(

return Hotel::model()->with( array(

  'city' => array(

    'select' => ','


  'country.currency' => array(

    'select' => array('value', 't.rate_min / value) AS rate_euros')

    'order' => 'rate_euros',


  'hotel_images' => array(

    'select' => '', 

    'group' => 'hotel_id'


) )->findAll( $criteria );

(partially tested/not tested)


Thank you Tommy, that worked very well, I tried something similar but I guess I was doing something wrong.

Another issue, related to this one, can I have the field "rate_euros" as part of the returned array when I do "findAll()"?

It seems like you need to declare rate_euros in the Currency model

public $rate_euros;

And to access the value, use -> instead of the dot notation used in the call to with(), e.g.

echo $models[$i]->country->currency->rate_euros;

(partially tested)


You are my hero… Thanks a lot Tommy, worked very well