为何自定义虚拟属性仅在部分October CMS模型中生效?
问题描述
我创建了两个模型——主模型Units可关联多个名称:
Units: id|unit desc and UnitNames: id|unit_id|name
在controller/units/config_relation.yaml中,我定义了关联片段以显示Unit关联的所有名称:
names: label: Names view: list: $/xxx/yyy/models/unitname/columns.yaml toolbarButtons: create showSorting: false defaultSort: column: valid_from direction: desc manage: form: $/xxx/yyy/models/unitname/fields.yaml
一切运行正常,但我需要添加虚拟字段:
public function getStupidAttribute() { return 'it is stupid'; }
该方法在UnitNames.php模型中可正常生效,但在Unit.php模型中完全无效,甚至未进入函数执行(我已在函数内添加die()测试)。请问这是什么原因?如何解决该问题?
原因与解决方案
原因
从配置文件格式判断是October CMS框架,关联列表渲染的是**关联模型(UnitNames)**的数据集,而非主模型(Units)的数据。主模型中定义的虚拟字段不会被关联列表加载调用,所以对应的方法不会执行。
解决方法
- 若要在关联列表中显示主模型的虚拟字段:
- 在
UnitNames模型中添加反向关联到Units:public function unit() { return $this->belongsTo(Units::class, 'unit_id'); } - 在
UnitNames的columns.yaml中配置列,通过反向关联获取主模型的虚拟字段:stupid: label: Stupid Field valueFrom: unit.stupid
- 在
- 若要在主模型详情页展示该虚拟字段:
在主模型Units的fields.yaml中添加该虚拟字段的配置:stupid: label: Stupid Field type: text readOnly: true
内容的提问来源于stack exchange,提问作者Tomasz Brzezina
相关产品推荐
相关产品推荐

