2016-10-11 87 views
0

我有一個名爲「設備」的MYSQL表。我已經成功完成了垃圾桶/蛋糕烘烤。事實上,我有自動生成的DevicesController.php完全可用。但我不知道如何計算表中的行。我已經試過:在CakePHP 3.x中,如何計算MySql表中的行數?

$conn = ConnectionManager::get('default'); 
$numRows = $conn->execute('select count(*) from devices'); 

$this->DeviceSetups = TableRegistry::get('Devices'); 
$numRows = $this->Devices->query('select count(*) from devices'); // both like this 
$numRows = $this->Devices->query('select count(*) from devices')->execute(); // and like this 

$this->DeviceSetups = TableRegistry::get('Devices'); 
$numRows = $this->Devices->find('count'); 

去通的mysql_query()是不是一個真正的好主意,因爲我擁有所有的接入信息已經設置在app.php供CakePHP使用。我嘗試了使用AnyModel的其他功能,但這種功能無效。

前2嘗試返回一個Cake \ Database \ Statement \ MysqlStatement不是一個整數與表中的行數。我已經諮詢了this答案和this答案並閱讀了CakePHP文檔。沒有任何東西似乎告訴我如何計算表格以及如何執行原始的My SQL命令字符串,然後訪問結果。

+0

如果你的db表叫做'devices',那麼表類名/別名通常應該是'Devices',而不是'DeviceSetups' !?除此之外它是'find() - > count()',沒有'count'發現者。 ** http://book.cakephp.org/3.0/en/orm/query-builder.html#returning-the-total-count-of-records** | ** http://book.cakephph.org/3.0/en/orm/retrieving-data-and-resultsets.html#getting-a-count-of-results** – ndm

+0

Thx,是的,這是一個錯字。我總是改變一些事情以確保我的開發保持專有。在這種情況下,我在變化之間處於中間狀態。 –

回答

0

如果你想計算在表中,那麼它應該如下所示。

$count = $this->find()->count(); 
    echo $count;