【问题标题】:Null value passed with select2 field type使用 select2 字段类型传递的空值
【发布时间】: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


【解决方案1】:

当您的主键不是典型的“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';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-03
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多