Monday 20 June 2011

CakePHP Trap: findAllBy() and find('all', ...)

I have a variable $productId. Comparing these two functions:


1. $pricelists = $this->PricesProduct->find('all',array('conditions'=>array('PricesProduct.id'=>$productId)));
$pricelists = $this->paginate('PricesProduct',$pricelists);


2. $pricelists = $this->PricesProduct->findAllByProductId($productId);
$pricelists = $this->paginate('PricesProduct',$pricelists);






If $productId = 1, the 2nd function will generate error but not for the 1st function.


Warning (512): SQL Error: 1054: Unknown column 'PricesProduct' in 'where clause' [CORE/cake/libs/model/datasources/dbo_source.php, line 684] 
Warning (2): Invalid argument supplied for foreach() [APP/views/...] 






Why?
I dont know the reason, but from the logs, two similar functions generated different sql codes:






For the 1st function:
1.  SELECT ... WHERE `PricesProduct`.`id` = 1,
which then generate normal sql code:
SELECT COUNT(*) AS ...  WHERE 1 = 1


For the 2nd function:
1. SELECT ... WHERE `PricesProduct`.`product_id` = 1,
which then generate the following problematic sql code:
SELECT COUNT(*) AS ... WHERE ((PricesProduct IN ('28', '1', '13' .....






I guess that findAllBy() is unable to generate a key for the find result, causing all data to be fed into the coming functions.


Therefore, it is advised to avoid using findAllBy() although it may have saved some programming time, yet it increase the risk of having to waste more time on debugging.
 
Sorry, it's my mistake that i myself is confused with two different functions that cause different result.
So, there is currently no trap in cakephp!

No comments: