濮阳杆衣贸易有限公司

主頁 > 知識(shí)庫 > 解決laravel id非自增 模型取回為0 的問題

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

熱門標(biāo)簽:青白江地圖標(biāo)注 沛縣400電話辦理 聊城電話外呼系統(tǒng)公司 銅川電話機(jī)器人價(jià)格 AI電話機(jī)器人OEM貼牌 江蘇電商外呼系統(tǒng)運(yùn)營(yíng)商 辦理重慶400電話 智能電話機(jī)器人好公司門薩維 德陽中江如何申請(qǐng)400開頭電話

問題

laravel5.2 中 如果一個(gè)模型的id 為string等非自增類型時(shí)候 使用模型的find方法 會(huì)返會(huì)0

樣例代碼:

  $a=Model::find('blcu');
 echo $a->id; //結(jié)果為0

原因查找

通過var_dump(a)發(fā)現(xiàn)a)發(fā)現(xiàn)a

["attributes":protected]=>
 array(16) {
 ["id"]=>
 string(4) "blcu"

也就是數(shù)據(jù)其實(shí)是讀取出來了 只是->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 的問題就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • Laravel統(tǒng)計(jì)一段時(shí)間間隔的數(shù)據(jù)方法
  • laravel實(shí)現(xiàn)按月或天或小時(shí)統(tǒng)計(jì)mysql數(shù)據(jù)的方法
  • laravel按天、按小時(shí),查詢數(shù)據(jù)的實(shí)例
  • 解決Laravel 使用insert插入數(shù)據(jù),字段created_at為0000的問題

標(biāo)簽:山南 鷹潭 烏魯木齊 南寧 濟(jì)寧 三亞 迪慶 赤峰

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《解決laravel id非自增 模型取回為0 的問題》,本文關(guān)鍵詞  解決,laravel,非自,增,模型,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《解決laravel id非自增 模型取回為0 的問題》相關(guān)的同類信息!
  • 本頁收集關(guān)于解決laravel id非自增 模型取回為0 的問題的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    扬中市| 广昌县| 哈尔滨市| 柳州市| 德阳市| 平顺县| 大同县| 疏勒县| 三穗县| 兴海县| 琼海市| 梅河口市| 海兴县| 封开县| 互助| 嵊州市| 陵水| 泗洪县| 新乡市| 香河县| 封丘县| 棋牌| 成武县| 达孜县| 无极县| 瑞昌市| 象山县| 平泉县| 泽库县| 邢台市| 翁源县| 伊川县| 新沂市| 容城县| 崇州市| 通河县| 竹溪县| 皋兰县| 怀仁县| 龙海市| 武汉市|