沃梦达 / 编程问答 / php问题 / 正文

Doctrine - 如何在 postSave() 事件中获取 SQL INSERT 查询?

Doctrine - how to get the SQL INSERT query, in the postSave() event?(Doctrine - 如何在 postSave() 事件中获取 SQL INSERT 查询?)

本文介绍了Doctrine - 如何在 postSave() 事件中获取 SQL INSERT 查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得在调用对象的 save() 方法时 Doctrine 生成的确切 SQL INSERT 查询.

I would like to get the exact SQL INSERT query that Doctrine generates when an object's save() method is called.

最好是在模型的 postSave() 事件中获取,并记录到 txt 文件中.

Preferably, I would like to get it in the postSave() event of the model and log it in a txt file.

例如:

<?php 
$user = new User(); // A Doctrine Model with timestampable behavior enabled
$user->first_name = 'Manny';
$user->last_name = 'Calavera';
$user->save();
?>

我想获取/记录以下 SQL 查询:

I want to get/log the following SQL query:

INSERT INTO user (first_name, last_name, created_at, updated_at) VALUES ('Manny', 'Calavera', '2010-08-03 12:00:00', '2010-08-03 12:00:00');

需要这个的背景是我希望稍后通过解析txt文件来批量导入数据.

The background for needing this, is that I wish to mass-import later the data by parsing the txt file.

推荐答案

我不认为有任何简单的方法可以做到这一点,因为 save() 的行为取决于一些不同的事情(如果你正在插入/更新).

I don't think there is any easy way to do this since the behaviour of save() varies depending on a few different things (if you're inserting/updating).

如果您已经创建了一个学说查询对象,那么您可以像这样调用 getSqlQuery() 方法:

If you had created a doctrine query object, then you can call the getSqlQuery() method like this:

$q = Doctrine_Query::create()
->select('u.id')
->from('User u');

echo $q->getSqlQuery();

但是 save() 是一个方法,而不是一个对象,所以这不起作用.我认为您必须编写一些代码来检测您是在插入还是更新并构建查询以即时登录,然后使用 save().

but the save() is a method, not an object so this won't work. I think you'll have to hack in some code to detect whether you're inserting or updating and build a query to log on the fly and then use save().

我知道这个建议并不理想,因为它没有准确"记录 save() 正在做什么,但出于您所说的目的,它应该仍然可以正常工作.

I know this suggestion is not ideal because it is not logging 'exactly' what save() is doing but for the purposes you stated it should still work just as well.

这篇关于Doctrine - 如何在 postSave() 事件中获取 SQL INSERT 查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Doctrine - 如何在 postSave() 事件中获取 SQL INSERT 查询?

基础教程推荐