问题描述
“我的产品”模型有一个code
外键,它指向一个代码模型,该模型也有一个code
列,但作为主键。在“产品的CRUD的创建”视图中,我创建了一个下拉字段,该字段允许我使用Select2字段类型从所有现有的代码中进行选择。
[
'label' => 'Code','type' => 'select2','name' => 'code',// the foreign key
'entity' => 'productCode',// the relationship's method
'model' => 'App\Models\Code','attribute' => 'code',// attribute that is shown in the dropdown
]
代码在下拉列表中正确显示,但是当我保存新产品时,代码字段作为空值存储在请求中。有人知道这个问题可能是什么吗?还是我弄错了这些?
这是产品模型中的关系:
public function productCode() {
return $this->belongsTo('App\Models\Code','code','code');
}
解决方法
当主键不是典型的“ id”列时,模型上需要primaryKey
属性;如果主键不是整数列,则需要keyType
属性:
将以下内容添加到您的App\Models\Code
模型中可以解决此问题:
/**
* The primary key for the model.
*
* @var string
*/
protected $primaryKey = 'code';
/**
* The "type" of the primary key
*
* @var string
*/
protected $keyType = 'string';