如何为所有模型动态更改检索到的数据
每次从数据库检索记录时,我都想拦截观察者中的数据,以便可以更改其值,然后将更改后的记录返回给控制器。
我目前有一个基本模型,我在其中设置了一个观察者,以便每次检索数据时,它都会触发以下代码:
public function retrieved($data)
{
$data->field = 'new value';
//return to controller
}
问题是检索到的事件发生在控制器接收数据之后,这意味着任何更改对模型所做的操作对控制器不可用。
无论如何,是否可以将这些更改后的数据发送回控制器。我是否以正确的方式处理这件事?对于我的目标有更好的解决方案吗?
Every time records are retrieved from the database, I want to intercept the data in the observer so that I can change its value, then return the altered records to the controller.
I currently have a base model where I have set up an observer, so that every time data is retrieved, it triggers the following bit of code :
public function retrieved($data)
{
$data->field = 'new value';
//return to controller
}
The problem is that the retrieved event happens after the controller receives the data, which means that any alterations made to the model are not available to the controller.
Is there anyway to send this altered data back to the controllers. Am I even going about this the right way ? Is there a better solution for my aims ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这种情况下,登录器似乎是一个不错的选择,因为您想在访问属性时修改结果。突变器是为了更新属性值时要修改值时。
要检索原始值,您可以使用
$ someobj--> getRaworiginal('属性');
,您可以将自定义属性附加到模型(使用class property
$ appends
)如果需要,可以与自己的登录器。In this case an accessor seem like a good choice since you want to modify the result when you access a property. A mutator is for when you want to modify the value when you update a property value.
To retrieve the original value you can use
$someObj->getRawOriginal('property');
Also, you can append custom properties to a model (using class property
$appends
) with their own accessors if needed.也许您应该查看 laravel突变器
由于您正在使用Laravel 8,所以您应该使用Laravel 8使用旧学校定义突变器的方式。
像这样:
使用相同的逻辑您也可以使用
setFieldAttribute
funtion。Maybe you should look at Laravel mutators
Since you are using laravel 8, you should use old school way of defining mutators.
Like this:
With same logic you can use
setFieldAttribute
funtion as well.我认为您需要的是变压器,它将转换您从数据库或某些源检索到的数据,然后可以在同一控制器中使用或传递到不同功能(控制器)。
看一下分形变压器
somemodeltransformer.php
somemodel。 php
$ transformeddata
I think what you need is a transformer, that will transform the data that you retrieved from the DB or some source, which can then be used within the same controller or passed on to different functions (controller).
Have a look at Fractal Transformers
SomeModelTransformer.php
SomeModel.php
$transformedData