简体   繁体   English

在 Doctrine 记录类中,从数据库查询相同的记录会覆盖该类中的属性

[英]From within a Doctrine record class, querying for the same record from the DB overwrites the properties within that class

In one of my Doctrine record classes, I have a preSave method that performs a check.在我的一个 Doctrine 记录类中,我有一个执行检查的preSave方法。 In this check, a query is done on the same table that my record belongs to.在此检查中,对我的记录所属的同一个表进行了查询。 This query will fetch one record from the table, and I use the hydrated result to compare to the current record represented by the class.此查询将从表中获取一条记录,我使用水合结果与类表示的当前记录进行比较。

In some cases, the fetched hydrated result will be the same record as the one I'm working with in the preSave check.在某些情况下,提取的水合结果将与我在preSave检查中使用的记录相同。 However, when this happens, any changes that I've made to the first record are reverted once the query is completed.但是,当发生这种情况时,一旦查询完成,我对第一条记录所做的任何更改都会恢复。

Why does this happen?为什么会发生这种情况? Is there a workaround?有解决方法吗?

Doctrine might be maintaining a single reference to the record object instance, and not creating a whole new instance in your preSave() method. Doctrine 可能会维护对记录对象实例的单个引用,而不是在您的 preSave() 方法中创建一个全新的实例。 So when the object is hydrated, any other variables of the same type in your code are 'refreshed'.因此,当对象水合时,代码中相同类型的任何其他变量都会“刷新”。

To verify this, inspect the object ID's of variables in your code using spl_object_hash() function.要验证这一点,请使用spl_object_hash()函数检查代码中变量的对象 ID。

Without seeing your code, workaround suggestions can vary, but one possible workaround is to hydrate an array in preSave():在没有看到您的代码的情况下,解决方法建议可能会有所不同,但一种可能的解决方法是在 preSave() 中对数组进行水合:

$query = Doctrine_Query::create()
->select('foo')
->from('Bar b')
->where('b.id = ?', $id);

$results = $query->execute(array(), Doctrine::HYDRATE_ARRAY);

You will lose the ability to use the result as an object, but you will be able to use the contents of the array for comparisons.您将无法将结果用作对象,但您将能够使用数组的内容进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM