gpt4 book ai didi

cakephp - 检查 CakePHP3.5 中是否存在记录

转载 作者:行者123 更新时间:2023-12-04 13:56:48 27 4
gpt4 key购买 nike

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

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

因为表是空的,如果表是空的,我想自定义这个,并在浏览器中调用一个新页面

最佳答案

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

如果您正在使用 Table::get()你可以 catch RecordNotFoundException :

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

如果您想使用 isEmpty() ,您需要使用常规查询:
$query = $this->Users->findById($uid);
if ($query->isEmpty()) {
// record doesn't exist
}

如果您实际上不需要结果,可以使用 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
  • 关于cakephp - 检查 CakePHP3.5 中是否存在记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48730987/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com