【问题标题】:Method to check record exist in database, and then if true return record in CakePHP?检查数据库中是否存在记录的方法,然后如果CakePHP中的记录为真则返回?
【发布时间】:2015-05-11 09:12:23
【问题描述】:

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

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

解决方案 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 次查询,是吗?),请给我答案以获得最佳解决方案。抱歉我的英语不好。

【问题讨论】:

    标签: php mysql cakephp


    【解决方案1】:

    不需要两个查询。

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

    如果您想要执行其他操作而不是显示未找到的错误,则捕获异常。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-13
        • 1970-01-01
        • 1970-01-01
        • 2023-03-18
        • 2019-11-27
        • 2013-08-07
        • 1970-01-01
        • 2013-12-27
        相关资源
        最近更新 更多