如何强制刷新yii中模型的值
假设我有与 B 相关的模型 A。
当我写:
$a = A::model()->findByPK(1);
$a->B->doSomething();
现在 B 可能会被更改(例如被其他用户更改)。当我写:
$a->B->doSomething();
它使用 B 的旧值时。我应该做什么来强制在 doSomething() 之前刷新 B 的值。
let's say I have model A with relation to B.
When I write:
$a = A::model()->findByPK(1);
$a->B->doSomething();
and now B may by changed (by other user for instance). When I write:
$a->B->doSomething();
it uses old values of B. What I should do to force to refresh value of B before doSomething().
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Yii 提供了一个刷新()方法我想这就是你想要的?
http://www.yiiframework.com/doc/api/CActiveRecord#refresh-detail
Yii provides a refresh() method I think thats what your looking for?
http://www.yiiframework.com/doc/api/CActiveRecord#refresh-detail
您可以通过以下方式获得刷新的“B”值:
第二个参数“true”要求 yii 从数据库重新加载关系。
You can get a refreshed 'B' value by saying:
The 2nd param "true" asks that yii reload the relation from the database.
在 Yii2 中它只是一个简单的
所以在这种情况下
unset($a->b)
In Yii2 its just a simple
so in this case
unset($a->b)
据我了解,当在 A 的模型中声明关系 B 时,当您调用 $a->B 时,对象 B 将从数据库中“延迟加载”。除非它被缓存(我不认为默认情况下它不会这样做),否则每次调用该关系时都应该获取 B 的新副本。
我会确保如果 doSomething() 正在更改 B 中的数据,您也可以在 B->doSomething() 中调用 $this->save() 。如果您更改 B 但不保存更改,那么当您再次查询 B 时,它将具有相同的旧内容。
如果您想在更改后但保存之前再次访问 B,则需要将其设置在 A 中的变量中以“缓存”它。否则,由于当您调用 $a->B 时它会从数据库获取新副本(并且您没有在 doSomething() 中保存更改),因此您将拥有旧数据。像这样的东西会起作用:
如果这是一个一般的并发问题(听起来可能是当你说“它被另一个用户更改了”时),你可能需要实现某种锁定机制,或者使用 mySql 事务(通过 Yii 的 CDbTransaction)来确保数据完整性。
如果这些都不起作用,也许执行“急切”加载也可以解决您的问题,如下所示:
As I understand it when the relationship B is declared in A's model, the object B is being "lazy loaded" from the database when you call $a->B. Unless it is being cached (which it doesn't do by default I don't think) it should be grabbing a fresh copy of B each time you call that relationship.
I would make sure that if doSomething() is changing the data in B that you also call $this->save() inside B->doSomething(). If you are changing B but not saving the changes then when you query for B again it will have the same old content.
If you want to access B again after you have changed it but before you have saved it, you will need to set it in a variable in A to "cache" it, sort of. Otherwise, since it's getting a fresh copy from the database when you call $a->B (and you didn't save the change in doSomething()), you will have the old data. Something like this will work instead:
If it is a general concurrency issue (which it sounds like it might be when you say "it's changed by another user"), you may need to implement some sort of lock mechanism, or use mySql transactions (via Yii's CDbTransaction) to ensure data integrity.
If none of this works, perhaps doing an "eager" load will fix your problem as well, like so:
$a->B->refresh();// 仅刷新 B
$a->refresh();// 刷新 a 以及包括“B”在内的所有关系
$a->B->refresh();// to refresh only B
$a->refresh();// to refresh a and all naturally all relations including "B"