如何在CakePHP中执行定制查询 [英] How to execute custom query in CakePHP

查看:131
本文介绍了如何在CakePHP中执行定制查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试在CakePHP框架中执行自定义查询,意味着而不是使用CakePHP语法,我想执行普通的SQL查询像 SELECT * FROM post ORDER BY id desc

I'm currently trying to execute custom queries in CakePHP framework, meaning instead of using CakePHP syntax, I'd like execute normal SQL query like SELECT * FROM post ORDER BY id desc.

我不知道该怎么做。我读了几个类似问题的答案,但仍然不能工作。

I cannot figure out how to do it. I read several answers to the similar questions, but it still doesn't work.

据我所知,我应该把函数放在:

As far as I understand I should put function like:

public function testx()
{
    $sql = "SELECT * FROM posts WORDER by id desc";
    return $this->query($sql);
}

到文件 Post 在目录 Model 中,然后输入以下代码:

to file Post in directory Model and then put this code:

$result = $this->Post->testx();

索引 c> PostsController 在控制器目录中。

to index function in PostsController in Controller directory.

以打印 View / Posts / index.ctp 中的数据。

感谢您提供任何答案。 / p>

Thanks in advance for any answer.

推荐答案

public function index(){
    $this->loadModel('Post'); //or you can load it in beforeFilter()
    $data=$this->Post->query('SELECT * FROM posts ORDER by id desc');
    $this->set('data',$data);
}

在您的视图文件 index.ctp 中。写下代码

In your view file index.ctp. Write Below Code

<?php
     if($data){
          echo "<pre>";
          print_r($data);
     }
     else
     {
          echo 'no data found';
     }
?>

这篇关于如何在CakePHP中执行定制查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆