检查数据库中是否存在记录的方法,如果为真 return 记录在 CakePHP 中?

Method to check record exist in database, and then if true return record in CakePHP?

我是 CakePHP 的新开发人员,我对这种情况感到困惑:

现在我有一个 table 用户模型用户,我想检查 id = 4 的记录是否存在:如果记录存在,return 它,如果不存在 return消息错误,我认为有2种方法:

解决方案 1:

$this->Model->id = 4;

if ($this->Model->exists()) {
 return $this->Model->read();
} else {
 return "ERROR";
}

解决方案 2:

$data = $this->Model->find('first', array(
 'conditions' => array('Model.id' => 4)
));

if (!empty($data)) {
 return $data;
} else {
 return "ERROR";
}

我不知道什么更好或更优化(我认为在解决方案 1 中 Cake 会执行 2 个查询,是吗?),请给我最好的答案 solution.Sorry 我的英语不好。

当然可以。对于 1,将有 two 个查询 - 第一个将是 count,第二个将 fetch 记录。

我更喜欢第二种方法。 运行 query 然后检查 empty 数据。

不需要二次查询

class FooModel extends Model {
    public function view($id) {
        $result = $this->find('first', [
            'conditions' => [
                $this->alias . '.' . $this->primaryKey => $id
            ]
        ]);
        if (empty($result)) {
            throw new \NotFoundException('Foo record not found');
        }
    }
    return $result;
}

然后只需在您的控制器操作中调用该方法:

public function view($id) {
    $this->set('foo', $this->FooModel->view($id));
}

如果你想做一些除了显示未找到错误之外的事情,或者捕获异常。