解决laravel id非自增 模型取回为0 的问题
时间:2022-07-27
本文章向大家介绍解决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 的问题就是小编分享给大家的全部内容了,希望能给大家一个参考。
- 高吞吐koa日志中间件
- 关于SQLRecoverableException问题的排查和分析(r4笔记第13天)
- Spring+SpringMVC+MyBatis+easyUI整合优化篇(十三)数据层优化-表规范、索引优化
- node中的Stream-Readable和Writeable解读
- Spring+SpringMVC+MyBatis+easyUI整合进阶篇(六)一定要RESTful吗?
- 深入node之Transform
- 巧用shell脚本统计磁盘使用情况(r4笔记第12天)
- 使用fasttext实现文本处理及文本预测
- 关于导入导出sequence(r4笔记第11天)
- Spring+SpringMVC+MyBatis整合进阶篇(四)RESTful实战(前端代码修改)
- Nodejs cluster模块深入探究
- org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression
- 巧用分析函数循序渐进解决实际问题 (r4笔记第10天)
- 支持多用户web终端实现及安全保障(nodejs)
- php概述
- php教程
- php环境搭建
- PHP书写格式
- php变量
- php常量
- PHP注释
- php数组
- php字符串 string
- PHP整型 integer
- PHP浮点型 float
- php布尔型
- php数据类型之数组
- php数据类型之对象
- php数据类型之null
- php数据类型之间的转换
- php运算符
- php表达式
- PHP循环控制
- PHP流程控制
- php函数
- php全局变量
- PHP魔术变量
- php命名空间
- php 日期
- PHP包含文件
- php文件
- PHP 文件上传
- php Cookies
- php Sessions
- php email
- php安全email
- php错误处理
- PHP异常处理
- php过滤器
- PHP 高级过滤器
- php json
- php 表单
- PHP MySQL 简介
- PHP 连接 MySQL
- php创建数据库
- php 创建表
- php mysq 插入数据
- PHP MySQL 插入多条数据
- PHP MySQL 预处理语句
- php mysql 读取数据
- php mysql where
- PHP MySQL Order By
- PHP MySQL Update
- PHP MySQL Delete
- php ODBC