Laravel 与select2字段类型一起传递的空值
我的产品型号有一个指向代码型号的Laravel 与select2字段类型一起传递的空值,laravel,eloquent,backpack-for-laravel,eloquent-relationship,laravel-backpack,Laravel,Eloquent,Backpack For Laravel,Eloquent Relationship,Laravel Backpack,我的产品型号有一个指向代码型号的code外键,它也有一个codecoulmn,但作为主键。在产品CRUD的Create视图中,我创建了一个下拉字段,允许我使用Select2字段类型从所有现有代码中进行选择 [ 'label' => 'Code', 'type' => 'select2', 'name' => 'code', // the foreign key 'entity' =>
code
外键,它也有一个code
coulmn,但作为主键。在产品CRUD的Create视图中,我创建了一个下拉字段,允许我使用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';
在您的
App\Models\code
model中,code
是该表的主键吗?如果是,您是否有类似protected$primaryKey='code'的属性代码>在那个模型上?如果不是,请尝试添加一个,如果上述猜测符合您的用法并且code
是字母数字值,您可能还需要添加protected$keyType='string'
到你的模型中。模型已经指定了上面的属性,对吗?好的,哇,我添加了你说的两行代码,现在它工作了,代码正确地存储在请求中,我不知道你必须在模型中指定主键和它的类型。非常感谢Wesley!你救了我一天