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

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

问题描述

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

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 (CakeDatasourceExceptionRecordNotFoundException $exeption) {
    // record doesn't exist
}

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

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
}

另见

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

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