How to convert SelectQuery object to SQL string?

I managed to print the line using the __toString () magic method, but in this line I see placeholders (for condition parameters), and it does not work as an SQL query.

I checked the documentation of this object, and also looked in Google, but could not find a working answer.

+1
source share
2 answers

Based on the comments (thanks to @Scuzzy for the inspiration), I wrote some simple code snippets to transform the object SelectQuery:

class ExportableSelectQuery {

    public static function toSql(SelectQuery $obj) {

        $_string = $obj->__toString();
        $_conditions = $obj->conditions();
        $_tables = $obj->getTables();
        $_fields = $obj->getFields();

        foreach($_tables as $k => $t) {
            if(!empty($t['alias'])) {
                $_string = str_replace('{' . $t['table'] . '}', $t['table'] . ' as', $_string);
            }
            else {
                $_string = str_replace('{' . $t['table'] . '}', $t['table'], $_string);
            }
        }

        foreach($_conditions as $k => $c) {
            if(is_int($c['value'])) {
                $_string = str_replace(':db_condition_placeholder_' . $k, $c['value'], $_string);
            }
            else {
                $_string = str_replace(':db_condition_placeholder_' . $k, "'" . $c['value'] . "'", $_string);
            }
        }

        //echo('<pre>');
        //var_dump($_fields);
        //var_dump($_conditions);
        //var_dump($_tables);
        //var_dump($_string);
        //echo('</pre>');
        //die();

        return $_string;
    }
}

Using this code is now simple (if you only have an object SelectQuery):

die(ExportableSelectQuery::toSql($query));

SelectQuery SQL, Drupal db_select SelectQuery, db_select, ExportableSelectQuery.

, , , , , , , .

+2

SQL , , "EntityFieldQyery", -

  • $query->entityCondition('entity_type', 'node')
          ->entityCondition('bundle', 'page')
          ->addTag('EFQDumper'); //<=== TAG
    
  • hook "query_TAG_alter"

    function YOURMODULE_query_EFQDumper_alter(QueryAlterableInterface $query)
    {
     //echo ExportableSelectQuery::toSql($query);
     //die();
    }
    

,

0

Source: https://habr.com/ru/post/1752193/


All Articles