溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何解決laravel id非自增模型取回為0的問題

發布時間:2021-07-21 09:55:18 來源:億速云 閱讀:148 作者:小新 欄目:開發技術

這篇文章給大家分享的是有關如何解決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的問題”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女