CakePHP 2.1.x - Run a query without any models in AppController

南楼画角 提交于 2019-12-03 11:08:44

问题


I am trying to run a query in AppController on a table that has no Model associated with it. I don't want to use a Model cause this query would fire on every request and I guess using a Model would make it a bit slower.

I found out in one forum that this can be achieved with the following code in CakePHP 1.3

$db = ConnectionManager::getInstance();
$conn = $db->getDataSource('default');
$conn->rawQuery($some_sql);

But this is not working in CakePHP 2.1.3. Any help would be appreciated. Thanks :)


回答1:


The getDataSource() method is static in CakePHP 2.x, so you should be able to use:

$db = ConnectionManager::getDataSource('default');
$db->rawQuery($some_sql);



回答2:


you should run this way

    App::uses('ConnectionManager', 'Model'); 
    $db = ConnectionManager::getDataSource('default');
    if (!$db->isConnected()) {
       $this->Session->setFlash(__('Could not connect to database.'), 'default',            array('class' => 'error'));
    } else {
        $db->rawQuery($some_sql);
    }



回答3:


rawQuery will not return data, use $db->query instead.

$db = ConnectionManager::getDataSource('default');
$data = $db->query($some_sql);


来源:https://stackoverflow.com/questions/11048293/cakephp-2-1-x-run-a-query-without-any-models-in-appcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!