mysql - How could I create a sub-query in cakePHP? -
how create sub-query in cakephp find method? example:
select *, (select count(*) table2 table2.field1 = table1.id) count table1 table1.field1 = 'value'
!!! table2.field1 = table1.id !!!
you can 1 of 2 ways:
1. use $this->model->query(...)
this allows execute sql directly using query posted above aware can make application quite brittle if database schema change. fastest.(documentation)
example
$this->model1->query("select * model;");
2. separate calls
this not fast option 1 give ability break query down number of steps. you're unlikely sql injection potential risk option 1.
example
$model1s = $this->model1->find ( 'all', array ( 'conditions' => array('model1.field1' => 'value') ) ); foreach($model1s $model1) { $model1['model2_count'] = $this->model2->find ( 'count', array ( 'conditions' => array ( 'model2.field1' => $model1['id'] ) ) ); }
Comments
Post a Comment