Laravel Nova:将字段动态绑定到模型上的JSON属性

问题描述 投票:0回答:1

Laravel Nova

对于特定项目,我想使用Nova Resource UI的强大功能和更灵活的数据模型。具体来说,我希望能够为存储在JSON数据库字段内的属性添加字段,而不是在表上。

具体细节:

数据库模型:报价(包括迁移)

public function up()
{
    Schema::create('quotations', function(Blueprint $table)
    {
        $table->bigInteger('id', true);
        $table->timestamps();
        $table->string('client_name', 100)->nullable();
        $table->string('client_surname', 100)->nullable();
        $table->string('status', 10)->nullable()->default('NEW');
        $table->text('data')->nullable();
    });
}

Nova资源

所以我可以定义一个“正常”的NOVA资源,并在App \ Nova \ Quotation中定义以下字段(*忽略状态):

public function fields(Request $request)
{
    return [
        Text::make('Client Name')->sortable(),
        Text::make('Client Surname')->sortable(),


    ];
}

现在我的“愿望”就是要有这样的效果,使用不存在的“绑定到”方法来说明我想要实现的目标

public function fields(Request $request)
{
    return [
        Text::make('Client Name')->sortable(),
        Text::make('Client Surname')->sortable(),

        //Fields bound into the JSON data property  
        Text::make('Client Id')->bindTo('data.client_id),
        Date::make('Client Date Of Birth')->bindTo('data.client_date_of_birth),

        //etc       


    ];
}

因此,当保存报价模型时,client_name和client_surname属性将按正常方式保存到数据库。但是client_id和client_date_of_birth应该保存到JSON数据属性。

我知道我可以在Quotation模型上设置Mutator

public function setClientIdAttribute($value)
{
      set_data($this->data,'client_id',$value);
}

然而,这仍然需要“非动态”Quoation模型。我希望能够在dynmiacally中向视图添加字段,而不必将Quotation模型更改为基础知识。一个真实的例子是,在生成报价之前,不同的产品具有不同的输入字段。然后,我可以轻松地在Nova资源中动态注入字段定义,同时保持数据库模型简单。

我也尝试了一个简单问题的答案:Laravel Model Dynamic Attribute

但是 - 由于Nova仍然在寻找桌面上的属性,所以提出的解决方案不起作用。

我希望得到一些关于如何解决这个要求的意见。

laravel eloquent laravel-nova
1个回答
2
投票

你可以这样做:

// Model
protected $casts = [
    'data' => 'array'
];

// Nova Resource  
Text::make('Client Id', 'data->client_id')->resolveUsing(function ($value) {
   return $value;
}),
© www.soinside.com 2019 - 2024. All rights reserved.