25

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?

4

2 回答 2

54

你可以做:

$fancyTable = TableRegistry::get('FancyTable');
$exists = $fancyTable->exists(['name' => 'fancy', 'active' => false]);
于 2014-08-04T08:52:54.200 回答
7

使用这样的东西:

if ($query->isEmpty()) {
    // Query or result set is empty
}
于 2015-10-07T05:39:26.643 回答