CakePHP 3 Raw SQL Query

后端 未结 3 970
慢半拍i
慢半拍i 2020-12-17 17:30

I\'m using CakePHP 3, I need to run a raw SQL query on multiple tables. In CakePHP 2, this could be done by using the query() method on any model ( $this->Messages-

3条回答
  •  感情败类
    2020-12-17 17:33

    The documentation for this is here: http://book.cakephp.org/3.0/en/orm/database-basics.html#executing-queries

    But what's not written there is how to execute it. Because it cost me a while, here is the solution for that:

    1.You need to add

    use Cake\Datasource\ConnectionManager;
    

    2.init the ConnectionManager (as mentioned above)

    $conn = ConnectionManager::get('my_connection');
    

    3.Execute your SQL with something like this

    $firstName = $conn->execute('SELECT firstname FROM users WHERE id = 1');
    

提交回复
热议问题