检查 CakePHP3.5 中是否存在记录 [英] Check if record exists in 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
}
另见
- 手册 > 数据库访问 &ORM > 检索数据 &结果集 > 通过主键获取单个实体
- Cookbook > 数据库访问 &ORM > 检索数据 &结果集 > 检查查询或结果集是否为空
- API > CakeDatasourceRepositoryInterface::exists()
- 手册 > 数据库访问 &ORM > 查询生成器 > 返回记录总数
这篇关于检查 CakePHP3.5 中是否存在记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!