【问题标题】:Laravel update method does not existLaravel 更新方法不存在
【发布时间】:2021-01-04 22:14:03
【问题描述】:

根据文档,我应该能够使用 update() https://laravel.com/docs/5.4/queries#updates 更新记录,但我收到了错误 Method update does not exist

Client::findOrFail($id)->update($request->all());

知道为什么吗?

【问题讨论】:

  • 使用->fill($request->all())->save()
  • 方法填充不存在...

标签: php laravel eloquent laravel-eloquent


【解决方案1】:

我认为这是因为您在单个模型对象上使用了查询构建器的方法。您不能这样做,因为findOrFail 方法返回一个与查询构建器的方法无关的对象。

这样做:Client::findOrFail($id)->first()->fill($request->all())->save();

【讨论】:

  • 您可以使用批量赋值:laravel.com/docs/5.4/eloquent#mass-assignment
  • 你确定你有一个真实的模型对象吗?用var_dump(Client::findOrFail($id));打印对象的内容并发送到这里
  • object(Illuminate\Database\Eloquent\Collection)#186 (1) { ["items":protected]=> array(1) { [0]=> object(App\client)# 196 (26) { ["guarded":protected]=> array(1) { [0]=> string(0) "" } ["connection":protected]=> string(6) "sqlite" ["table ":protected]=> NULL ["primaryKey":protected]=> string(2) "id" ["keyType":protected]=> string(3) "int" ["incrementing"]=> bool(true) ["with":protected]=> array(0) { } ["withCount":protected]=> array(0) { } ["perPage":protected]=> int(15) ["exists"]=> bool(true) ["wasRecentlyCreated"]=> bool(false) ["attributes":protected]=> array(5...
  • 我明白了。您将获得一个集合而不是单个对象。这不应该是这样,但是,使用这个:Client::findOrFail($id)->first()->...
  • 因为这里更新功能适用于单个对象,因为您通过主键更新单行
【解决方案2】:

试试这个:

Client::find($id)->update($request->all());

或者你可以使用这个:

Client::where('id',$id)->first()->update($request->all());

【讨论】:

  • 使用 dd(Client::find($id)); 进行调试以查看您得到的结果
  • 似乎没问题:Collection {#186 ▼ #items: array:1 [▼ 0 => client {#196 ▼ #guarded: array:1 [▶] #connection: "sqlite" # table: null #primaryKey: "id" #keyType: "int" +incrementing: true #with: [] #withCount: [] #perPage: 15 +exists: true +wasRecentlyCreated: false #attributes: array:5 [▼ " id" => "5" "name" => "Aafasdfasf" "active" => "Yes" "created_at" => "2017-09-08 11:13:33" "updated_at" => "2017-09- 08 11:13:33" ] 等
  • 你在这里得到一个集合,它必须是一个对象
猜你喜欢
  • 2018-07-01
  • 2017-09-14
  • 2016-12-07
  • 2022-11-23
  • 2019-05-10
  • 2017-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多