Laravel模型在保存时添加了多余的数据

13

我有一些像这样的代码

    $editStuState = StuAtt::where('studentId' , '=' , $id)->first();
    $editStuState -> leave +=1;
    $editStuState -> present = $editStuState -> present-1;
    $editStuState->update();
                            //OR
    $editStuState->save();
    return 'this is good';

我无法保存或更新我的数据, 当我删除与更新和保存有关的行时,它可以打印文本。

这是 dd($editStuState) 数据

StuAtt {#382 ▼
  #table: "stu_attendance"
  #connection: "mysql"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:7 [▼
    "id" => "7"
    "studentId" => "1"
    "present" => "2"
    "absent" => "1"
    "leave" => "10"
    "created_at" => "2018-04-16 11:17:41.176898"
    "updated_at" => "2018-04-16 06:47:41.000000"
  ]
  #original: array:7 [▼
    "id" => "7"
    "studentId" => "1"
    "present" => "2"
    "absent" => "1"
    "leave" => "10"
    "created_at" => "2018-04-16 11:17:41.176898"
    "updated_at" => "2018-04-16 06:47:41.000000"
  ]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
  #guarded: array:1 [▶]
}

我也遇到了这个错误,它来自laravel 5.6。

Translated Text:

我也遇到了这个错误,它来自laravel 5.6。

InvalidArgumentException
Trailing data
5个回答

8
如果您正在使用Postgres,则必须向您的模型添加一些代码行。这是由于Postgres中的TIME WITH TIMEZONE造成的。
请阅读 Date Mutators,因为Laravel已经支持此功能,只需在您的模型中输入下面一行代码来覆盖该模型的默认dateFormat: https://laravel.com/docs/5.7/eloquent-mutators#date-mutators 转到您的App/Model(在app文件夹下,例如User、SomeModel),添加下面一行代码:
protected $dateFormat = 'Y-m-d H:i:sO';

最好的


1

将您的代码更改为:

$editStuState = StuAtt::where('studentId' , '=' , $id)->first();
$editStuState -> leave +=1;
$editStuState -> present = $editStuState -> present-1;
$editStuState->update();
                        //OR
$editStuState->save();
return 'this is good';

To:

$editStuState = StuAtt::where('studentId' , '=' , $id)->first();
$editStuState -> leave +=1;
$editStuState -> present = $editStuState -> present-1;
$editStuState->save();
return 'this is good';

方法->update(...)用于批量更新,请查看批量更新


我说我检查了它们两个,得到了相同的错误。你看到//OR了吗? - Nasser Ali Karimi
尝试在您的模型中添加 *protected $dateFormat = 'Y-m-d H:i:s';*。 - Aleksa Nikolic

1
如果您的数据库是Postgres并且字段是Timestamp,有时Carbon无法转换为默认格式(不带毫秒)。如果不需要毫秒,请更新字段内容以不包含毫秒部分。
UPDATE YOURTABLE SET created_at = date_trunc('seconds', created_at),
updated_at = date_trunc('seconds', updated_at)

这将规范化没有毫秒的时间戳字段。


0

我有同样的问题,但是我把列名改成了creation_date,问题得到解决。


0
在我的情况下,问题出在表中created_atupdated_at的长度上。在Navicat表设计中是这样的:

enter image description here

将其更改为0并保存更改:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接