【问题标题】:How to use custom MySQL queries in CakePHP?如何在 CakePHP 中使用自定义 MySQL 查询?
【发布时间】:2013-12-23 10:51:51
【问题描述】:

我现在在做cakephp,请解释一下cakephp中自定义mysql查询的过程。 我们必须使用

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

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

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

流程正确吗?请解释一下代码...

【问题讨论】:

    标签: cakephp


    【解决方案1】:

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

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

    这是一个完整的模型方法,用于根据 id OR 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;
    }
    

    【讨论】:

      【解决方案2】:

      你的解决方案是正确的,让我更详细地阐述它

      第一种解决方案

      在你的控制器中

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

      第二个解决方案

      在你的模型类中

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

      在控制器类中

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

      【讨论】:

      • 第二个就是你正在做的问题。不客气
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-23
      相关资源
      最近更新 更多