欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

解決laravel id非自增 模型取回為0 的問(wèn)題

 更新時(shí)間:2019年10月11日 09:14:54   作者:D_T  
今天小編就為大家分享一篇解決laravel id非自增 模型取回為0 的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

問(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)文章

最新評(píng)論