【问题标题】:Laravel - Serious Issue with soft deletingLaravel - 软删除的严重问题
【发布时间】:2015-12-08 22:16:04
【问题描述】:

我有 2 个模型,车辆和制造商。制造商与车辆具有一对多的关系。我在两个模型上都启用了软删除。我有一个所有车辆的 html 表,其中显示了 html 表中的 title、slug、manufacturer_id 和 deleted_at(laravel 默认)字段。

现在,当我从其页面软删除车辆时,一切正常,并且显示所有车辆 + 软删除的车辆。同样,如果我删除该车辆的制造商,我仍然会看到所有制造商 + 软删除的制造商。现在当我返回车辆页面时出现问题,我收到一个错误提示

Trying to get property of non-object 

这意味着它正在寻找不再存在的manufacturer_id。这是我获得所有车辆的雄辩查询

// Vehicle Controller
/* This query basically gets all fields in the first column from vehicle model
   and all the fields in the second column from manufacturer model*/

   $this->vehicle->getAllWithTrash( 
       ['id', 'title', 'description', 'is_active', 'manufacturer_id', 'created_at', 'updated_at', 'deleted_at'],
       ['title', 'id'] 
   ) );


// Eloquent Repository
   public function getAllWithTrash( $columns1 = array('*'), $columns2 = array('*') ){

        return Vehicle::withTrashed()->with(['manufacturer' => function($q) use ($columns2){
                $q->select($columns2);
        }])->get($columns1)->toJson();

    }

所以我想修改这个查询,所以它会获取所有制造商的所有车辆+软删除的车辆,无论它们是否被软删除。

【问题讨论】:

    标签: laravel laravel-5 eloquent laravel-5.1


    【解决方案1】:

    查看withTrashed() 函数

    如上所述,软删除的模型将被自动排除 从查询结果。但是,您可以强制软删除模型 在查询中使用 withTrashed 方法出现在结果集中:

    $flights = App\Flight::withTrashed()->where('account_id', 1)->get();

    withTrashed 方法也可以用于关系查询:

    $flight->history()->withTrashed()->get();

    试试这个:

    // Eloquent Repository
       public function getAllWithTrash( $columns1 = array('*'), $columns2 = array('*') ){
    
            return Vehicle::withTrashed()->with(['manufacturer' => function($q) use ($columns2){
                    $q->withTrashed()->select($columns2);
            }])->get($columns1)->toJson();
    
        }
    

    【讨论】:

      猜你喜欢
      • 2016-03-05
      • 2019-04-20
      • 1970-01-01
      • 2014-04-20
      • 1970-01-01
      • 2017-12-16
      • 2013-06-19
      • 2015-10-06
      • 2014-10-23
      相关资源
      最近更新 更多