繁体   English   中英

检查记录的方法是否存在于数据库中,然后如果是CakePHP中的真实返回记录?

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

我是CakePHP的新开发者,我对此案感到困惑:

现在我有一个用户模型用户表,我想检查id = 4的记录是否存在:如果记录存在,则返回它,如果没有返回消息错误,我认为有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蛋糕将做2个查询,是吗?),请给我答案为最好的解决方案。请为我的英语不好。

不需要两个查询。

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));
}

或者,如果您想要执行除了显示未找到错误之外的其他操作,请捕获异常。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM