在 Yii 中跟踪 CreatedBy 和 UpdatedBy

发布于 2025-01-06 17:21:19 字数 263 浏览 1 评论 0原文

我有这样的数据库

=== Group ===
id
member_id
decsription

=== Member ===
id
name
description

一切工作正常。现在我扩展了我的组表并添加了一些额外的字段,例如 created_byupdated_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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

只涨不跌 2025-01-13 17:21:19

您可以在 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.

蘸点软妹酱 2025-01-13 17:21:19

如果它是一个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

动听の歌 2025-01-13 17:21:19

确保您的 created_byupdated_by 字段为 DATETIME,然后当您对它们运行 UPDATE 查询以更新数据时,请确保传递 NOW() 不带任何引号。这会将这些字段更新为当前的DATETIME,例如2012-02-17 10:00:00

希望这有帮助。

Make sure your created_by and updated_by fields are DATETIME then when you run UPDATE queries against them to update the data, make sure you pass NOW() without any quotes. This will update those fields to the current DATETIME e.g. 2012-02-17 10:00:00.

Hope this helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文