【发布时间】:2014-12-29 16:48:30
【问题描述】:
我有一个名为Multilingual 的特征,它使用模型的lang 和translation_of 属性(另见https://stackoverflow.com/a/7299777/1453912)来提供实体的多种翻译。
现在我想在调用$model->toArray() 时从模型中隐藏translation_of 字段,这很容易通过将其添加到$hidden 属性来完成。像这样:
class Model {
use Multilingual;
protected $hidden = ['translation_of'];
}
但为了保持原始模型干净,我想通过 used trait 添加隐藏字段。
我试过了:
-
在特征中添加
protected $hidden = ['translation_of'];,这是不允许的:Undefined: trait declaration of property 'hidden' is incompatible with previous declaration而且也不是很可扩展(我认为它将被类的
$hidden属性覆盖......) -
为 trait 添加启动方法:
static function bootMultilingual() { static::$hidden[] = 'translation_of'; }由于范围的原因,这(我怀疑)也是不允许的。
有什么想法可以做到这一点吗?
请帮忙!
注意:为了保持动态,我认为可以通过两种方式完成:
- 内部:
$this->hidden[] = 'translation_of'; - 对外:
$model->setHidden(array_merge($model->getHidden(), ['translation_of']));
【问题讨论】:
标签: laravel model attributes eloquent traits