如何将SelectQuery对象转换为SQL字符串? [英] How to convert SelectQuery object to SQL string?

查看:107
本文介绍了如何将SelectQuery对象转换为SQL字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设法使用__toString()魔术方法打印一个字符串,但是在这个字符串中,我看到占位符(对于条件参数),并且它不能用作SQL查询。

I managed to print a string using __toString() magic method, but in this string I see placeholders (for conditions params), and it doesn't work as SQL query.

我检查过文档这个对象也是google,但是找不到工作的答案。

I checked documentation of this object, and also looked in google, but couldn't find a working answer.

推荐答案

根据问题的意见(谢谢@Scuzzy的灵感)我写了一些简单的代码来转换 SelectQuery 对象:

Basing on question's comments (thanks @Scuzzy for inspiration) I wrote some simple piece of code to convert SelectQuery object:

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;
    }
}

此代码的使用现在很简单(如果只有$ SelectQuery 对象某处):

Usage of this code is now simple (if you only have SelectQuery object somewhere):

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

我正在考虑扩展原始 SelectQuery 对象,并提供获取SQL代码的方法,但Drupal的 db_select 函数返回 SelectQuery ,所以我必须更改 db_select 函数或将返回的对象转换为 ExportableSelectQuery

I was thinking about extending original SelectQuery object, and provide method to get SQL code, but Drupal's db_select function returns SelectQuery, so I will have to either change db_select function or cast returned object to ExportableSelectQuery.

还这可能不是我可以写的最好的解决方案,但是假设时间和目的的限制解决了我的问题,只要罚款。

Also this is not probably best solution I could write, but assuming limit of time and purpose it solved my problem just fine.

这篇关于如何将SelectQuery对象转换为SQL字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆