在 Yii 中跟踪 CreatedBy 和 UpdatedBy
我有这样的数据库
=== Group ===
id
member_id
decsription
=== Member ===
id
name
description
一切工作正常。现在我扩展了我的组表并添加了一些额外的字段,例如 created_by
和 updated_by
,通过它们我可以跟踪谁创建了和谁做出了改变。那么为了实现我应该做什么以及如何做到这一点?任何帮助和建议将非常感激。
I have the database like this
=== Group ===
id
member_id
decsription
=== Member ===
id
name
description
Everything is working fine.Now I extended my Group table and added some extra field like created_by
and updated_by
,by which I can track who has created and who has made the changes.So to achieve what should I do and how to do that?Any help and suggestions will be highly appreciable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在 AR 类中扩展 beforeSave / beforeUpdate 并简单地设置 $this->updated_by = Yii::app()->user->getId();更新时。如果您重写这些方法,请确保完成后返回 true,以免阻止保存。您还可以将created_at和updated_at设置为new CDbExpression('NOW()');以便这些也始终是最新的。
希望这有帮助!
注意:并不是说让 AR 模型了解当前登录的用户是件好事,但它应该可以正常工作并且值得考虑。
You could extend beforeSave / beforeUpdate in your AR class and simply set $this->updated_by = Yii::app()->user->getId(); on update. If you override these methods, make sure to return true when you are done so that you do not prevent save. You can also set created_at and updated_at to new CDbExpression('NOW()'); so that these are always up to date as well.
Hope this helps!
Note: Not saying it's very nice to have your AR models know about the currently signed in user, but it should work just fine and it's worth considering.
如果它是一个Web应用程序,那么您可以使用会话将用户信息放入会话中并访问用户ID并将其保留在数据库中(确保您有用户表的外键)
如果您使用Spring框架,您可以查看使用拦截器来访问和设置每个数据库更新调用的用户 ID
If its a web application , then you can use the session to put the user info into the session and access the user id and persist that in the database ( make sure that you have foreign key to the user table )
If you are using Spring framework , you can look at using interceptors to access and set the user id for every database update call
确保您的
created_by
和updated_by
字段为 DATETIME,然后当您对它们运行UPDATE
查询以更新数据时,请确保传递NOW()
不带任何引号。这会将这些字段更新为当前的DATETIME
,例如2012-02-17 10:00:00
。希望这有帮助。
Make sure your
created_by
andupdated_by
fields are DATETIME then when you runUPDATE
queries against them to update the data, make sure you passNOW()
without any quotes. This will update those fields to the currentDATETIME
e.g.2012-02-17 10:00:00
.Hope this helps.