CakePHP 3 Raw SQL Query

后端 未结 3 980
慢半拍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:38

    First you need to add the ConnectionManager:

    use Cake\Datasource\ConnectionManager;
    

    Then you need to get your connection like so:

    // my_connection is defined in your database config
    $conn = ConnectionManager::get('my_connection');
    

    More info: http://book.cakephp.org/3.0/en/orm/database-basics.html#creating-connections-at-runtime

    After that you can run a custom query like this:

    $stmt = $conn->execute('UPDATE posts SET published = ? WHERE id = ?', [1, 2]);
    

    More info: http://book.cakephp.org/3.0/en/orm/database-basics.html#executing-queries

    And then you are ready to fetch the row(s) like this:

    // Read one row.
    $row = $stmt->fetch('assoc');
    
    // Read all rows.
    $rows = $stmt->fetchAll('assoc');
    
    // Read rows through iteration.
    foreach ($rows as $row) {
        // Do work
    }
    

    More info: http://book.cakephp.org/3.0/en/orm/database-basics.html#executing-fetching-rows

提交回复
热议问题