1. 程式人生 > 實用技巧 >解決laravel id非自增 模型取回為0 的問題

解決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 的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援碼農教程。