【发布时间】:2021-01-05 04:16:34
【问题描述】:
我的 Product 模型有一个 code 外键,它指向一个 Code 模型,它也有一个 code 库,但作为主键。在 Product 的 CRUD 的 Create 视图中,我创建了一个下拉字段,允许我使用 Select2 字段类型从所有现有的 Codes 中进行选择。
[
'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
]
代码在下拉列表中正确显示,但是当我保存新产品时,代码字段作为空值存储在请求中。任何人都知道问题可能是什么?或者如果我弄错了?
这是 Product 模型中的关系:
public function productCode() {
return $this->belongsTo('App\Models\Code', 'code', 'code');
}
【问题讨论】:
-
在您的
App\Models\Code模型中,code是该表的主键吗?如果是,您在该模型上是否有类似protected $primaryKey = 'code';的属性?如果没有,您可以尝试添加一个和 -
如果以上猜测符合您的使用情况且
code是字母数字值,您可能还需要将protected $keyType = 'string';添加到您的模型中。 -
而且模型确实已经指定了上面的属性,对吗?
-
好的哇,我添加了你说的两行代码,现在它可以工作了,代码正确存储在请求中,我不知道你必须指定主键及其在模型中也输入
-
非常感谢韦斯利!您节省了一天
标签: laravel eloquent laravel-backpack eloquent-relationship