Check if record exists in CakePHP3.5

大城市里の小女人 提交于 2019-12-19 07:09:11

问题


The Following Code returns only a error :Record not found in table "users"

if($this->Users->get($uid)->isEmpty()) {
            //do something
        }

Because the Table is empty, i want to customize this if the table is empty, and call a new page in browser


回答1:


Table::get() will immediately evaluate the query and return an entity, or throw an exception if the record with the given primary key doesn't exist, ie it doesn't return a query, you cannot call isEmpty() on the result.

If you are using Table::get() you can catch the RecordNotFoundException:

try {
    $user = $this->Users->get($uid);
    // ...
} catch (\Cake\Datasource\Exception\RecordNotFoundException $exeption) {
    // record doesn't exist
}

If you wanted to use isEmpty(), you'd need to use a regular query:

$query = $this->Users->findById($uid);
if ($query->isEmpty()) {
    // record doesn't exist
}

If you don't actually need the result, you can use Table::exists():

$exists = $this->Users->exists(['id' => $uid]);
if ($exists !== true) {
    // record doesn't exist
}

or a COUNT query:

$count = $this->Users->findById($uid)->count();
if ($count !== 1) {
    // record doesn't exist
}

See also

  • Cookbook > Database Access & ORM > Retrieving Data & Results Sets > Getting a Single Entity by Primary Key
  • Cookbook > Database Access & ORM > Retrieving Data & Results Sets > Checking if a Query or ResultSet is Empty
  • API > \Cake\Datasource\RepositoryInterface::exists()
  • Cookbook > Database Access & ORM > Query Builder > Returning the Total Count of Records


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

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