如何在CakePHP中使用自定义MySQL查询?

时间:2013-12-23 10:51:51

标签: cakephp

我现在正在开发cakephp。请解释蛋糕php中自定义mysql查询的过程。 我们必须使用

编写查询
$this->Model->query();

然后我将它返回到controller.In控制器中,我在特定的函数中加载了模型,我调用了函数并将该函数设置为像这样查看

$this->set('post',$this->User->get());

这是正确的过程吗?请解释一下代码......

2 个答案:

答案 0 :(得分:3)

你想用这种方式写什么查询?可以使用CakePHP ORM编写几乎所有查询。使用CakePHP的查询构建函数是首选方法。

所有获取操作的数据也应该在模型中完成。请参阅Separation of Concerns

这是一个完整的模型方法,用于根据其ID或slug获取用户记录。

public function view($userId, $options = []) {
    $defaults = array(
        'contain' => array(),
        'conditions' => array(
            'OR' => array(
                $this->alias . '.' . $this->primaryKey => $userId,
                $this->alias . '.slug' => $userId,
            ),
            $this->alias . '.email_verified' => 1
        ),
    );

    $result = $this->find('first', Hash::merge($defaults, $options));

    if (empty($result)) {
        throw new NotFoundException(__d('user_tools', 'User not found!'));
    }

    return $result;
}

<强>控制器:

public function view($userId = null) {
    $this->set('user', $this->User->view($userId);
}

替代但非首选模式方法来获取数据

public function view($userId, $options = []) {
    $result = $this->query(/* Your query here */);

    if (empty($result)) {
        throw new NotFoundException(__d('user_tools', 'User not found!'));
    }

    return $result;
}

答案 1 :(得分:0)

您的解决方案是正确的,让我更详细地说明它

第一个解决方案

在您的控制器中

$arrayTemp =array();
$arrayTemp = $this->ModelName->query(' Your Query String ');
$this->set('post',$arrayTemp);

第二个解决方案

在您的模型类中

function returnDate(){
   return $this->query('Your Query String')
}

在Controller类

    $arrayTemp = $this->ModelName->returnDate();
    $this->set('post',$arrayTemp);
}
相关问题