这篇文章给大家分享的是有关如何解决laravel 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; 即可解决
感谢各位的阅读!关于“如何解决laravel id非自增模型取回为0的问题”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。