ar">
解决laravel id非自增 模型取回为0 的问题
Laravel  /  管理员 发布于 8年前   202
问题 laravel5.2 中 如果一个模型的id 为string等非自增类型时候 使用模型的find方法 会返会0 样例代码: 原因查找 通过var_dump(a)发现a)发现a 也就是数据其实是读取出来了 只是->id取得时候 变成了0 查看Model的 getAttribute 方法,此方法指向了 getAttributeValue 查看 castAttribute 如果 >getCastType(‘id') 如果为int 则 (int)$value 查看 >getCastType getCasts 最中改变值得代码: 结论 Model的$incrementing 默认为true 当我们使用id为 非自增的时候 laravel 会把字符串转为int 所以输出了0 解决方案 给模型生命的时候添加 public $incrementing=false; 即可解决 以上这篇解决laravel id非自增 模型取回为0 的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。 $a=Model::find('blcu'); echo $a->id; //结果为0
["attributes":protected]=> array(16) { ["id"]=> string(4) "blcu"
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; }
protected function castAttribute($key, $value) { if (is_null($value)) { return $value; } switch ($this->getCastType($key)) { case 'int': case 'integer': return (int) $value; //这一行
protected function getCastType($key) { return trim(strtolower($this->getCasts()[$key])); }
public function getCasts() { if ($this->getIncrementing()) { //如果Model了的$incrementing字段为True return array_merge([ $this->getKeyName() => 'int', //返回id=>'int' ], $this->casts); } return $this->casts; }
您可能感兴趣的文章:
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号