SELECT DISTINCT in CakePHP
Even though CakePHP’s model already includes many of the database query functions, I found that the SELECT DISTINCT was missing. Ok, I know that you can always do it using either Model->query('SELECT DISTINCT or c1, c2)Model->findAll(null, 'DISTINCT but that would be like saying use c1, c2‘)Model->query() instead of Model->findAll().
The cool thing in CakePHP is that you can add your own functions to use in your app on top of the ones that come bundled in the core. For the Model, you just create an ‘app_model.php’ file that you place in our app’s main folder. The empty file should look like this:
/**
* Custom AppModel that adds functionality to the core Model
*/
class AppModel extends Model
{
//empty
}
Now inside your new AppModel class, add the following function:
/**
* Returns a resultset array with DISTINCT fields from database matching given conditions.
*
* @param mixed $conditions SQL conditions as a string or as an array('field' =>'value',...)
* @param mixed $fields Either a single string of a field name, or an array of field names
* @return array Array of records
*/
function findDistinct($conditions = null, $fields = null)
{
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$str = 'DISTINCT ';
if (!is_array($fields))
{
$str .= '`' . $fields . '`';
}
else
{
foreach ($fields as $field)
{
$str .= '`' . $field . '`, ';
}
$str = substr($str, 0, -2);
}
$queryData = array(
'conditions' => $conditions,
'fields' => $str,
);
$data = $db->read($this, $queryData, false);
return $data;
}
You can now use Model->findDistinct('c1') or Model->findDistinct(array('c1', 'c2', 'c3')) to retrieve DISTINCT columns values.
Hoping you find it useful.
September 1st, 2007 at 8:17 am
[…] Loud Baking » Blog Archive » SELECT DISTINCT in CakePHP A method for providing district queries in CakePHP by extending AppModel (tags: cakephp sql distinct appmodel) […]
September 28th, 2007 at 2:47 am
Sweet. I just found your blog on @thekeyboards blogroll and am amazed I hadn’t seen your posts referred to anywhere else.
Great resource. Keep it up.. and incidentally continue the Auth series. I particularly would like to see an implementation outside of the ACL meme.
September 28th, 2007 at 4:06 am
@Abba: Welcome! I am the kind of silent guy - been “blogtrotting” on CakePHP related sites for a couple months, only the other day did I finally leave a comment. But yea, it’s mainly a resource for my staff and if it can help others, then that’s a plus.
I was first intending on continuing the tutorial that covers ALL the AuthComponent’s authorization methods on the blog but gwoo suggested it goes on the Bakery - still waiting on him to send me the last corrections he’d like to see, but it’s ready.
Regards,
Jad
June 15th, 2008 at 3:31 am
a pure joy! I can only echo Abba’s comment keep up the great work