Virtual Fields as aliases to other Model field – SQL: Unknown Column Error-Collection of common programming errors
I’m new to an existing Cake project where we are trying to use a virtualField within a model to alias another model field. In Context:
class Product extends AppModel {
var $name = 'Product';
var $hasOne = array('ProductPrice');
var $virtualFields = array(
'price' => 'ProductPrice.current_price'
);
// Typical fields in the database for Product. id, name, etc.
}
class ProductPrice extends AppModel {
var $name = 'ProductPrice';
var $belongsTo = array('Product');
// Fields are product_id, current_price
}
The ProductPrice model is for a view in the database that contains different price tiers with a current_price column allowing retrieval of the current price of the product. When accessing the Product model via something like:
$this->Product->find('all' ....);
I don’t have any problems with getting the price field. The problem is if the query to Product is done indirectly through something like
$this->Inventory->find('all');
We get:
SQL Error: 1054: Unknown column 'ProductPrice.current_price' in 'field list' [CORE/cake/libs/model/datasources
/dbo_source.php, line 681]
I know that the issue is that the SQL generated by the Inventory query does not attempt to join the ProductPrice view. I assumed that this would happen automagically via the Product model as it knows it “hasOne” ProductPrice.
I’ve tried setting “recursive” on the Inventory model to 2,1, etc. with no success.
What am I missing?