CakePHP 3 Raw SQL Query

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

    The question is already very old, but I still find it frequently. Here is a solution for CAKEPHP 3.6 and (short) for newer PHP Versions.

    It is not necessary to use the ConnectionManager get function and often it does not make sense, as the connection name may not be known at all. Every table has its / a connection which one can get with getConnection ().

    If you are already in the Messages Table (src/Model/Table/MessagesTable.php), you can simply use the Connection

    $con = $this->Messages->getConnection();
    

    If you are not there (what your code would suggest with TableRegistry::get(), you can do that with this table as well

    // $aumTable is declared in question
    $con = $aumTable->getConnection();
    

    then you can execute a RAW query as shown above:

    $result = $con->execute ();
    // short 
    $result = $this->Messages->getConnection()->execute ('Select * from ...')
    // or ($aumTable is declared in question)
    $result = $aumTable->getConnection()->execute ('Select * from ...');
    

提交回复
热议问题