如何输出/记录Fuel PHP的Orm查询生成的sql查询?

时间:2013-04-22 11:55:34

标签: fuelphp

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

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

3 个答案:

答案 0 :(得分:9)

执行任何运行查询的操作后,可以使用以下任何一个

\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'

答案 1 :(得分: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, 在您的应用程序配置中启用。

希望我的上述解决方案能解决您的问题

答案 2 :(得分:0)

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

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