Check if record exists in CakePHP3

流过昼夜 提交于 2019-12-17 23:24:45

问题


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?


回答1:


You can do:

$fancyTable = TableRegistry::get('FancyTable');
$exists = $fancyTable->exists(['name' => 'fancy', 'active' => false]);



回答2:


Use something like this:

if ($query->isEmpty()) {
    // Query or result set is empty
}


来源:https://stackoverflow.com/questions/25065005/check-if-record-exists-in-cakephp3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!