解決laravel id非自增 模型取回為0 的問(wèn)題
問(wèn)題
laravel5.2 中 如果一個(gè)模型的id 為string等非自增類型時(shí)候 使用模型的find方法 會(huì)返會(huì)0
樣例代碼:
$a=Model::find('blcu'); echo $a->id; //結(jié)果為0
原因查找
通過(guò)var_dump(a)發(fā)現(xiàn)a)發(fā)現(xiàn)a
["attributes":protected]=> array(16) { ["id"]=> string(4) "blcu"
也就是數(shù)據(jù)其實(shí)是讀取出來(lái)了 只是->id取得時(shí)候 變成了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); //這一行是導(dǎo)致數(shù)值改變的地方 } 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; }
結(jié)論
Model的$incrementing 默認(rèn)為true
當(dāng)我們使用id為 非自增的時(shí)候 laravel 會(huì)把字符串轉(zhuǎn)為int 所以輸出了0
解決方案
給模型生命的時(shí)候添加
public $incrementing=false; 即可解決
以上這篇解決laravel id非自增 模型取回為0 的問(wèn)題就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
YII框架學(xué)習(xí)筆記之命名空間、操作響應(yīng)與視圖操作示例
這篇文章主要介紹了YII框架學(xué)習(xí)筆記之命名空間、操作響應(yīng)與視圖操作,結(jié)合實(shí)例形式分析了Yii框架中命名空間、操作響應(yīng)以及視圖的簡(jiǎn)單操作技巧與相關(guān)注意事項(xiàng),需要的朋友可以參考下2019-04-04php 從一個(gè)數(shù)組中隨機(jī)的取出若干個(gè)不同的數(shù)實(shí)例
本文章向碼農(nóng)介紹php從一個(gè)不重復(fù)的數(shù)組中隨機(jī)的取出若干個(gè)不同的元素,難點(diǎn)是防止在取數(shù)的時(shí)候出現(xiàn)已經(jīng)取到過(guò)的情況(特別是取到最后),需要盡可能的降低碰撞,需要的朋友可以參考下2016-12-12Apache啟動(dòng)報(bào)錯(cuò)No space left on device: AH00023該怎么解決
最近有朋友說(shuō):Apache啟動(dòng)報(bào)錯(cuò)No space left on device: AH00023,是怎么回事,該怎么解決呢?經(jīng)過(guò)小編的一番折騰,問(wèn)題解決,下面把解決辦法分享給大家,需要的朋友可以參考下2015-10-10PHP array_key_exists檢查鍵名或索引是否存在于數(shù)組中的實(shí)現(xiàn)方法
下面小編就為大家?guī)?lái)一篇PHP array_key_exists檢查鍵名或索引是否存在于數(shù)組中的實(shí)現(xiàn)方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-06-06php遞歸函數(shù)三種實(shí)現(xiàn)方法及如何實(shí)現(xiàn)數(shù)字累加
實(shí)現(xiàn)遞歸函數(shù)有哪些方法呢?如何用遞歸函數(shù)實(shí)現(xiàn)數(shù)字累加?這篇文章就主要介紹php遞歸函數(shù)三種實(shí)現(xiàn)方法及如何實(shí)現(xiàn)數(shù)字累加,需要的朋友可以參考下。2015-08-08destoon之URL Rewrite(偽靜態(tài))設(shè)置方法詳解
這篇文章主要介紹了destoon的URL Rewrite(偽靜態(tài))設(shè)置方法,需要的朋友可以參考下2014-06-06