Print SQL query of ORM query builder in cakephp3
Asked Answered
C

3

7

How to print ORM query

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

For example print =>

SELECT * FROM comments WHERE article_id IN (comments);
Cateyed answered 18/3, 2016 at 8:57 Comment(0)
M
12

Wrapping your ORM query result with the debug function will show the SQL and bound params:

debug($query);

You can also similarly look at the query results with the debug function.See CakePHP 3: retrieving data and result sets — Debugging Queries and ResultSets

Mnemonic answered 18/3, 2016 at 9:59 Comment(2)
Do you know how to print only sql part of it?Cateyed
Did you try string casting it? (string)$query.Microbalance
A
11

what about $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());

and result:

.../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'
Affecting answered 14/10, 2017 at 6:57 Comment(1)
The official DebugKit plugin has the helper functions that you need.Mauramauralia
C
3

I prefer this:

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);
Cateyed answered 19/3, 2016 at 1:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.