如何在 Laravel 模型上延迟加载自定义属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39980760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to lazy load a custom attribute on a Laravel model?
提问by Andy Noelker
Is there any possible way to lazy load a custom attribute on a Laravel model withoutloading it every time by using the appends
property? I am looking for something akin to way that you can lazy load Eloquent relationships.
是否有任何可能的方法可以在 Laravel 模型上延迟加载自定义属性,而无需每次都使用该appends
属性加载它?我正在寻找类似于您可以延迟加载 Eloquent 关系的方式。
For instance, given this accessor method on a model:
例如,给定模型上的这个访问器方法:
public function getFooAttribute(){
return 'bar';
}
I would love to be able to do something like this:
我希望能够做这样的事情:
$model = MyModel::all();
$model->loadAttribute('foo');
This question is notthe same thing as Add a custom attribute to a Laravel / Eloquent model on load?because that wants to load a custom attribute on every model load - I am looking to lazy loadthe attribute only when specified.
这个问题是不是一回事自定义属性添加到负载的Laravel /雄辩的模式?因为它想在每个模型加载时加载一个自定义属性 - 我希望仅在指定时延迟加载该属性。
I suppose I could assign a property to the model instance with the same name as the custom attribute, but this has the performance downside of calling the accessor method twice, might have unintended side effects if that accessor affects class properties, and just feels dirty.
我想我可以为模型实例分配一个与自定义属性同名的属性,但这有调用访问器方法两次的性能下降,如果访问器影响类属性,可能会产生意想不到的副作用,只是感觉很脏。
$model = MyModel::all();
$model->foo = $model->foo;
Does anyone have a better way of handling this?
有没有人有更好的方法来处理这个问题?
回答by Hammerbot
Is this for serialization? You could use the append()
method on the Model instance:
这是为了序列化吗?您可以append()
在 Model 实例上使用该方法:
$model = MyModel::all();
$model->append('foo');
The append
method can also take an array as a parameter.
该append
方法还可以将数组作为参数。
回答by Rob
Something like this should work...
像这样的事情应该工作......
public function loadAttribute($name) {
$method = sprintf('get%sAttribute', ucwords($name));
$this->attributes[$name] = $this->$method();
}