問(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è)參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:- 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的問(wèn)題