我想请问如何在模型类上创建动态属性。假设我有一个如下所示的表结构。请看以下代码。
Schema::create('materials', function (Blueprint $table) {
$table->increments('id');
$table->string('sp_number');
$table->string('factory');
$table->text('dynamic_fields')->comment('All description of the material will saved as json');
$table->timestamps();
});
我的表结构中有一个名为“dynamic_fields”的列,用于存储字段的JSON字符串。以下是JSON结构的示例:
[
{
"name":"COLOR WAY",
"value":"ASDFF12"
},
{
"name":"DESCRIPTION",
"value":"agg2sd12"
},
{
"name":"REF NUM",
"value":"121312"
}
]
我想要访问我动态字段中的一个字段,例如"颜色方案"。
在我的模型中,我希望像这样访问动态字段中的"颜色方案"字段。
$material->color_way;
有人能给我展示如何做吗?
$table->json
。不需要是文本。然后,根据您的示例,您正在尝试从json中访问值,而不是键。 Eloquent模型中的访问器函数可以编写为getColorWayAttribute()
,这将使您可以使用$material->color_way
。 - nakov