這篇文章給大家分享的是有關如何解決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的問題”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。