天天看點

php 傳回非自增長主鍵,解決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 的問題就是小編分享給大家的全部内容了,希望能給大家一個參考,也希望大家多多支援腳本之家。