如何在不重写全部代码的情况下实现软删除模型的可编辑列更新?
软删除模型与可编辑列的适配解决方案
问题核心原因
saveMinorUpdate方法中使用findOrFail时未携带withTrashed(),无法查询到已软删除的模型;- 自定义的
saveMinorUpdateEntry返回了save()的布尔结果,而非模型实例,导致后续代码调用模型方法时触发Call to a member function withFakes() on bool错误。
无需重写完整saveMinorUpdate的解决方案
方案1:通过操作初始化方法调整查询范围 + 修正返回值
- 在你的CrudController中添加
setupSaveMinorUpdateOperation方法,让查询自动包含软删除记录:
public function setupSaveMinorUpdateOperation() { // 覆盖模型查询逻辑,包含软删除的记录 $this->crud->setModel($this->crud->getModel()->withTrashed()); }
- 修正
saveMinorUpdateEntry方法,返回更新后的模型实例而非布尔值:
public function saveMinorUpdateEntry() { $entry = $this->crud->getModel()->withTrashed()->findOrFail(request('id')); $entry->{request('attribute')} = request('value'); $entry->save(); return $entry; // 返回模型实例,而非save()的布尔结果 }
方案2:重写模型获取方法实现全局控制
如果希望所有saveMinorUpdate操作都自动适配软删除模型,可以重写控制器的getModel方法:
public function getModel() { $model = parent::getModel(); // 判断当前为saveMinorUpdate操作时,添加软删除查询范围 if (request()->route()->getActionMethod() === 'saveMinorUpdate') { return $model->withTrashed(); } return $model; }
同样需要配合上述修正后的saveMinorUpdateEntry方法使用。
内容的提问来源于stack exchange,提问作者Mocean
相关产品推荐
相关产品推荐

