You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不重写全部代码的情况下实现软删除模型的可编辑列更新?

软删除模型与可编辑列的适配解决方案

问题核心原因

  1. saveMinorUpdate方法中使用findOrFail时未携带withTrashed(),无法查询到已软删除的模型;
  2. 自定义的saveMinorUpdateEntry返回了save()的布尔结果,而非模型实例,导致后续代码调用模型方法时触发Call to a member function withFakes() on bool错误。

无需重写完整saveMinorUpdate的解决方案

方案1:通过操作初始化方法调整查询范围 + 修正返回值

  1. 在你的CrudController中添加setupSaveMinorUpdateOperation方法,让查询自动包含软删除记录:
public function setupSaveMinorUpdateOperation()
{
    // 覆盖模型查询逻辑,包含软删除的记录
    $this->crud->setModel($this->crud->getModel()->withTrashed());
}
  1. 修正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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 16:04:59