Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print SQL query of ORM query builder in cakephp3

How to print ORM query

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

For example print =>

SELECT * FROM comments WHERE article_id IN (comments);
like image 498
Fury Avatar asked Mar 18 '16 08:03

Fury


Video Answer


3 Answers

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

like image 57
Yosyp Schwab Avatar answered Oct 21 '22 18:10

Yosyp Schwab


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'
like image 26
MSS Avatar answered Oct 21 '22 17:10

MSS


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);
like image 3
Fury Avatar answered Oct 21 '22 17:10

Fury