6

是否有某种方法可以记录或输出从 aModel_Orm::query()或 a生成的 mysql 查询字符串Model_Orm::find()

我有一个复合体Orm::query()没有给我预期的结果,我想知道为什么!

4

3 回答 3

10

在执行任何运行查询的操作之后,无论是以下任何一项

\Model_Something::find('all');
\Model_Something::query()...
\DB::query()...
\DB::select()...

您可以使用

echo \DB::last_query();

查看上次运行的内容,无论您使用哪种方式查询数据库。

取自生产代码的工作示例:

$product = Model_Product::find('all', array(
     'related' => array(
              'i18ns',
     ),
     'where' => array(
              array('i18ns.variant_slug', $slug)
     )
));

echo \DB::last_query();
exit;

SELECT `t0`.`family_id` AS `t0_c0`, `t0`.`type_id` AS `t0_c1`,
       `t0`.`sort_weight` AS `t0_c2`, `t0`.`active` AS `t0_c3`,
       `t0`.`attribute_set` AS `t0_c4`, `t0`.`created_at` AS `t0_c5`,
       `t0`.`updated_at` AS `t0_c6`, `t0`.`site_id` AS `t0_c7`,
       `t0`.`temporal_start` AS `t0_c8`, `t0`.`temporal_end` AS `t0_c9`,
       `t0`.`id` AS `t0_c10`, `t1`.`id` AS `t1_c0`, `t1`.`product_id` AS `t1_c1`,
       `t1`.`language_id` AS `t1_c2`, `t1`.`slug` AS `t1_c3`,
       `t1`.`variant_slug` AS `t1_c4`, `t1`.`title` AS `t1_c5`,
       `t1`.`description` AS `t1_c6`, `t1`.`temporal_start` AS `t1_c7`,
       `t1`.`temporal_end` AS `t1_c8`
FROM `products` AS `t0`
LEFT JOIN `product_i18n` AS `t1`
     ON (`t0`.`id` = `t1`.`product_id`)
WHERE `t1`.`variant_slug` = 'test-product'
于 2013-04-23T09:04:08.507 回答
2

有一些方法可以实现这一点,如果您只想打印您构建的复杂查询,请使用 get_query(); ORM 查询类的方法。

下面是打印查询的示例代码。

$queryToExecute = Model_Article::query()
        ->select('author')
        ->where('date', '<', time())
        ->where('draft', '=', 1);


// This will print the query which is actually executed by your ORM 
echo $queryToExecute->get_query();

如果要记录查询并执行

$queryString = $queryToExecute->get_query();
Log::info("Query that is executed {$queryString} ");

如果您想分析您的查询的性能,您应该使用DB profiler,通过在您的应用程序配置中启用。

希望我上面的解决方案能解决你的问题

于 2013-04-22T17:28:56.133 回答
0

执行查询后,可以使用 follow 语句

echo \Database_Connection::instance(Model_Foo::$_connection)->last_query;

于 2013-10-09T07:31:32.280 回答