Code前端首页关于Code前端联系我们

修复 laravel ID 非递增模型问题 0

terry 2年前 (2023-09-25) 阅读数 49 #后端开发

如果模型 ID 为非递增类型,例如字符串,则模型查找器方法返回 0

示例代码:

  $a=Model::find('blcu');
 echo $a->id; //结果为0

原因搜索

检测到) 通过 var_dump(a) 找到 a

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

这说明确实读取了数据,但是在取 Model 时 ->id 变成了 0,这个方法指向 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 if>getCastType('id') 如果它是 int then(int)$ value

 protected function castAttribute($key, $value)
 {
  if (is_null($value)) {
   return $value;
  }

  switch ($this->getCastType($key)) { 
   case 'int':
   case 'integer':
    return (int) $value; //这一行

View>getCastType

 protected function getCastType($key)
 {
  return trim(strtolower($this->getCasts()[$key]));
 }

getCasts

值得更改的代码模型增量结论

$ 默认为 true

如果我们使用 ID 作为非 auto增量,laravel 将字符串转换为 int,因此输出为 0

Solution

$growth= false 赋予模型生命;可以解决

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门