Laravel模型保存模型时的尾随数据

Nas*_*imi 10 php model trailing invalidargumentexception laravel-5

我有一些像这样的代码

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

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

这是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 [?]
}
Run Code Online (Sandbox Code Playgroud)

我也得到了这个错误形式laravel 5.6它

InvalidArgumentException
Trailing data
Run Code Online (Sandbox Code Playgroud)

我根据我的研究逐行检查我的代码,我认为与Carbon无关.我应该怎么解决这个问题?

Nas*_*imi 13

尾随数据是Carbon错误,因为您可能使用Postgres并且您的日期返回毫秒.

"created_at" => "2018-04-19 07:01:19.929554"
Run Code Online (Sandbox Code Playgroud)

您可以将以下方法添加到(基础)模型中.

public function getDateFormat()
{
     return 'Y-m-d H:i:s.u';
}
Run Code Online (Sandbox Code Playgroud)


Tey*_*non 8

如果您使用 Postgres,则必须向模型添加一些行。这是因为 Postgres 中的 TIME WITH TIMEZONE 。

另请阅读Date MutatorsLaravel 已经支持此功能,只需在您的模型中放置以下行即可覆盖该模型的默认日期格式:https : //laravel.com/docs/5.7/eloquent-mutators#date-mutators

转到您的应用程序/模型(在app文件夹下,exp.User,SomeModel)添加以下行:

protected $dateFormat = 'Y-m-d H:i:sO';
Run Code Online (Sandbox Code Playgroud)

最好的事物


小智 1

更改您的代码,来自:

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

到:

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

Method ->update(...)用于批量更新,勾选Mass Updates