检查CakePHP3.5中是否存在记录 [英] Check if record exists in CakePHP3.5

查看:89
本文介绍了检查CakePHP3.5中是否存在记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码仅返回错误:在用户表中找不到记录

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

推荐答案

Table :: get()将立即评估查询并返回一个实体,或者如果具有给定主键的记录不正确则抛出异常不存在,即它不返回查询,您不能在结果上调用 isEmpty()

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.

如果您使用的是 Table :: get(),则可以捕获 RecordNotFoundException

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
}

如果要使用 isEmpty(), d需要使用常规查询:

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
}

如果实际上不需要结果,则可以使用 Table :: exists()

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
}

COUNT 查询:

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

另请参见

  • 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

这篇关于检查CakePHP3.5中是否存在记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆