Laravel eloquent:更新模型及其关系
问题描述
使用 eloquent 模型,您只需调用
With an eloquent model you can update data simply by calling
但不幸的是,这不会更新关系.
如果你也想更新关系,你需要手动分配每个值并调用 push() 然后:
If you want to update the relationships too you will need to assign each value manually and call push() then:
在整个过程中,如果您要分配大量数据,它会变得一团糟.
Althrough this works it will become a mess if you have a lot of data to assign.
我正在寻找类似的东西
有人可以帮我吗?
推荐答案
您可以实施观察者模式来捕捉更新"的 eloquent 事件.
You can implement the observer pattern to catch the "updating" eloquent's event.
首先,创建一个观察者类:
First, create an observer class:
然后将其分配给您的模型
Then assign it to your model
当你调用 update 方法时,更新"事件将被触发,因此观察者将被触发.
And when you will call the update method, the "updating" event will be fired, so the observer will be triggered.
有关事件的完整列表,请参阅 laravel 文档.
See the laravel documentation for the full list of events.
这篇关于Laravel eloquent:更新模型及其关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!