Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if record exists in CakePHP3

In CakePHP 2 I always used empty to check if there any result.

<?php
$result = $this->Modelname->find('first', ['conditions' => ['field' => 'value'] ] );
if ( empty($result) ) {
// Bad Request
}

In CakePHP 3 it looks weird to me.

$fancyTable = TableRegistry::get('FancyTable');        
$query = $fancyTable->find()->where(['name' => 'fancy', 'active' => 0]);          

if ( 0 === $query->count() ) {
    // Bad Request
}

Is this the right way?

like image 866
bastey Avatar asked Jul 31 '14 17:07

bastey


2 Answers

You can do:

$fancyTable = TableRegistry::get('FancyTable');
$exists = $fancyTable->exists(['name' => 'fancy', 'active' => false]);
like image 147
José Lorenzo Rodríguez Avatar answered Nov 07 '22 11:11

José Lorenzo Rodríguez


Use something like this:

if ($query->isEmpty()) {
    // Query or result set is empty
}
like image 7
Krunal Dave Avatar answered Nov 07 '22 11:11

Krunal Dave