laravel id非自增 模型取回为0 的解决方案
2018-01-30 20:57
686 查看
id为非自增 模型取回为0 的解决方案
问题
laravel5.2 中 如果一个模型的id 为string等非自增类型时候 使用模型的find方法 会返会0样例代码: $a=Model::find('blcu'); echo $a->id; //结果为0
原因查找
通过var_dump(a)发现a)发现a["attributes":protected]=> array(16) { ["id"]=> string(4) "blcu"
也就是数据其实是读取出来了 只是->id取得时候 变成了0
查看Model的 getAttribute 方法,此方法指向了 getAttributeValue
public function getAttributeValue($key) { $value = $this->getAttributeFromArray($key); if ($this->hasGetMutator($key)) { return $this->mutateAttribute($key, $value); } if ($this->hasCast($key)) { return $this->castAttribute($key, $value); //这一行是导致数值改变的地方 } if (in_array($key, $this->getDates()) && ! is_null($value)) { return $this->asDateTime($value); } return $value; }
查看 castAttribute 如果 >getCastType(‘id’) 如果为int 则 (int)$value
protected function castAttribute($key, $value) { if (is_null($value)) { return $value; } switch ($this->getCastType($key)) { case 'int': case 'integer': return (int) $value; //这一行
查看 >getCastType
protected function getCastType($key) { return trim(strtolower($this->getCasts()[$key])); }
getCasts
最中改变值得代码:
public function getCasts() { if ($this->getIncrementing()) { //如果Model了的$incrementing字段为True return array_merge([ $this->getKeyName() => 'int', //返回id=>'int' ], $this->casts); } return $this->casts; }
结论
Model的$incrementing 默认为true当我们使用id为 非自增的时候 laravel 会把字符串转为int 所以输出了0
解决方案
给模型生命的时候添加public $incrementing=false;即可解决
扫描二维码,多一个朋友,
关于技术的那些事儿,我们一起探讨。
WeChat:
相关文章推荐
- laravel使用模型怎样获得最后一条插入的ID
- 主键id是自增的,插入数据还是提示 SQL 不能插入重复键
- laravel一键生成模型、控制器、视图、表单验证类等等
- laravel学习笔记---关于模型
- 微软解决方案框架(MSF) -- MSF过程模型
- Laravel数据模型层M错误MassAssignmentException in Model.php line 407: username
- 导出excel,id参数太长解决方案
- 对于执行Get-SPWeb遇到错误“Cannot find an SPWeb object with Id or Url”的解决方案
- SharePoint解决方案开发模型系列 - 团队的建立 推荐
- Laravel中创建模型文件
- 7.在用selenium2(WebDriver)做自动化时候,如果有的元素通过ID,Xpath,CSS selector不能定位的解决方案。
- C# 最基本的涉及模式(单例模式) C#种死锁:事务(进程 ID 112)与另一个进程被死锁在 锁 | 通信缓冲区 资源上,并且已被选作死锁牺牲品。请重新运行该事务,解决方案: C#关闭应用程序时如何关闭子线程 C#中 ThreadStart和ParameterizedThreadStart区别
- laravel中的ORM模型修改created_at,updated_at,deleted_at三个时间字段类型
- laravel中使用vue热加载时 Cannot read property 'call' of undefined BUG解决方案
- laravel模型
- VS中添加新项 数据选项卡下没有ADO.NET实体数据模型解决方案
- Hibernate的ID生成策略/联合主键解决方案
- dedecms(织梦)自定义表单后台显示不全 自定义模型当中添加自定义字段后在后台添加内容后不显示解决方案
- Laravel5.1 模型--查询作用域
- 微软解决方案框架 - MSF的团队模型