Laravel Nova使用belongsTo保存资源字段

时间:2019-07-31 10:44:34

标签: laravel laravel-nova

我想在Laravel Nova中保存资源。

我实际上有2种资源和2种模型:

客户 CustomerType

客户具有以下字段:

Text::make('Vat')
   ->rules('required', 'string', 'max:254')
   ->creationRules('unique:customers,vat')
   ->updateRules('unique:customers,vat,{{resourceId}}'),

BelongsTo::make('Type', 'customer_type', 'App\Nova\CustomerType'),

“客户模型”与 customer_type 有关联:

public function customer_type(){
        return $this->belongsTo('App\Models\CustomerType', 'id', 'type');
    }

当我打开创建客户资源视图时,我可以在选择框中正确看到类型列表,但是当我尝试设置类型并将其保存时返回SQL错误:

  

SQLSTATE [HY000]:常规错误:1364字段“类型”没有   默认值(SQL:插入customersvatidname,   updated_atcreated_at)值(vat,?,test,2019-07-31 10:41:05,   2019-07-31 10:41:05))

如何将类型添加到nova资源保存中?

我还尝试将Relationship的名称从 customer_type 更改为 type ,但返回相同的错误。

我的数据库现在是:

客户

  • id
  • vat
  • 类型

customer_type 表:

  • id

  • sl

编辑

我也试过放

BelongsTo::make('CustomerType'),

在现场和客户模型中:

public function customertype(){
        return $this->belongsTo('App\Models\CustomerType', 'id', 'type');
    }

但是发生了同样的错误。

1 个答案:

答案 0 :(得分:0)

对于其他开发人员。

我发现了我的错误。

在我的模型中,我反转了关系的外键和所有者键:

代替:

public function customertype(){
        return $this->belongsTo('App\Models\CustomerType', 'id', 'type');
    }

应该

public function customertype(){
        return $this->belongsTo('App\Models\CustomerType', 'type', 'id');
    }