在cakephp3中打印ORM查询生成器的SQL查询

时间:2016-03-18 08:57:25

标签: cakephp cakephp-3.x

如何打印ORM查询

$query = $articles->find('all')->contain(['Comments']);

例如print =>

SELECT * FROM comments WHERE article_id IN (comments);

3 个答案:

答案 0 :(得分:7)

$query->sql()怎么办?

$qb = $this->Person->find()->select(["id", "text" => "concat(Name,' ',Family)"])
            ->where(['id >' => 0])
            ->where($query ? ["OR" => $filters] : null)
            ->limit(10);
dd($qb->sql());

和结果:

.../src/Controller/ClientController.php (line 86)
'SELECT Person.id AS `Person__id`, concat(Name,' ',Family) AS `text` FROM person Person WHERE (id > :c0 AND (Family like '%sam%' OR Name like '%sam%' OR Family like '%sam%' OR Name like '%sam%')) LIMIT 10'

答案 1 :(得分:6)

使用debug函数包装ORM查询结果将显示SQL和绑定参数:

debug($query);

您还可以使用调试功能查看查询结果。请参阅CakePHP 3: retrieving data and result sets — Debugging Queries and ResultSets

答案 2 :(得分:1)

我更喜欢这个:

public function __debugInfo()
    {
        return [
            'query' => $this->_query,
            'items' => $this->toArray(),
        ];
    }

// Print the query
debug($query->__debugInfo()['sql']);

// Prints this
SELECT * FROM comments WHERE article_id IN (comments);