Laravel - 软删除的严重问题

ome*_*ooq 1 laravel eloquent laravel-5 laravel-5.1

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

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

Trying to get property of non-object 
Run Code Online (Sandbox Code Playgroud)

这意味着它正在寻找不再存在的制造商 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();

    }
Run Code Online (Sandbox Code Playgroud)

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

Ami*_*Bar 6

查看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();

    }
Run Code Online (Sandbox Code Playgroud)