laravel自定义主键

165次阅读
没有评论

订单 Order 模型覆盖主键后

protected $primaryKey = ‘no’;
关联模型 OrderItem 保存数据时报错(该模型主键获取到的是 Order 模型 id 主键数据,非定义的 no 字段的数据)

操作一:删除设置的覆盖主键

protected $primaryKey = ‘no’;
设置关联如下,提交数据正常

public function items() {
return $this->hasMany(OrderItem::class,’order_id’,’no’);
}
无奈,重读 快速入门《Laravel 5.6 中文文档》 Eloquent 模型约定 — 主键 部分

使用非递增或者非数字的主键,则必须在模型上设置 public $incrementing = false 。
最后在原基础上加一句,解决问题。

protected $primaryKey = ‘no’;
public $incrementing = false;//加上这句
知识点:
非递增或者非数字的主键,需要加上

public $incrementing = false;
非整数主键,需要加上

protected $keyType = “string”;

正文完
可以使用微信扫码关注公众号(ID:xzluomor)
post-qrcode
 
评论(没有评论)