如何在 Laravel Nova 中忽略数据库操作中的字段

How to ignore field from database operation in Laravel Nova

我正在使用 Laravel Nova 开发 Web 应用程序。 Laravel Nova 很新。我现在遇到数据库关系和字段问题。我喜欢从数据库操作中忽略一个字段。这是我的场景。

在作业资源中,我有这个字段方法

public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),
            Text::make('Name', 'name'),
            Text::make('Email', 'email'),
            Select::make('Contract Types')->options($array_of_options)//I want to ignore this field
        ];
    }

如您所见,最后一个字段是合同类型。

当我从 Dashboard 创建新作业时,它会抛出错误,因为作业模型上没有 contract_types 列。我喜欢在数据库操作中忽略该字段。我怎样才能得到它?

根据文档 https://nova.laravel.com/docs/1.0/resources/fields.html#showing-hiding-fields

Select::make('Contract Types')
    ->options($array_of_options)
    ->hideWhenCreating()

接受的答案并不完全正确。它可以防止将值存储在数据库中,但也可以完全隐藏表单中的字段。在一些奇怪的情况下,您可能想要显示未存储的字段。

我的建议是将以下内容添加到资源中(或者如果您希望在多个资源中添加,则将其放在更可重用的地方):

public static function fill(NovaRequest $request, $model)
{
    return static::fillFields(
        $request, $model,
        (new static($model))->creationFieldsWithoutReadonly($request)->reject(function ($field) use ($request) {
            return in_array('ignoreOnSaving', $field->meta);
        })
    );
}

您可以在相关字段中添加:

->withMeta(['ignoreOnSaving'])

这将为您提供一个无需保存到模型中即可填写的字段。

您可以对字段数据进行自定义处理,只需使用字段 class 的 fillUsing() 方法即可。一个例子

public function fields(Request $request)
{
    return [
        ID::make()->sortable(),
        Text::make('Name', 'name'),
        Text::make('Email', 'email'),
        Select::make('Contract Types', 'unique_key_for_model')
            ->options($array_of_options)
            ->fillUsing(function(NovaRequest $request, $model, $attribute, $requestAttribute) {
                /*
                    $request->input('unique_key_for_model') // Value of the field
                    $model->unique_key_for_model // DOES NOT exists, so no errors happens
                */
                // or just return null;
                return null;
            }),
    ];
}