根据您的需要,您将需要 softDeletes 在您的 User 模型中以及它们各自在数据库中的表,现在这解决了您没有从表中删除用户只需添加 deleted_at 列的第一个问题。
编辑:当您使用Zizaco\Entrust\Traits\EntrustUserTrait 时,您需要让您的用户模型看起来像这样:
class User extends Model implements AuthenticatableInterface
{
use Authenticatable;
use EntrustUserTrait { restore as private restoreA; }
use SoftDeletes { restore as private restoreB; }
public function restore()
{
$this->restoreA();
$this->restoreB();
}
}
有关此错误的更多信息,您需要查看:https://github.com/Zizaco/entrust/issues/742
所以现在来到第二点,可以使用withTrashed() 来检索已删除模型的帖子,例如:
$user = User::withTrashed()->all();
$user = User::withTrashed()->where('id', 1);
$posts = $user->posts()->get();
// Or do your relational things
即使您想将其分配给不同的用户,您也需要创建一个新用户并将更新方法应用于所有关系模型,同时删除该用户,这似乎是个坏主意。
编辑:
所以在这种情况下,您可以:
$oldUser = User::find($id);
$user = User::find($botID); // Find the bot user
$oldFoods = $oldUser->food()->get();
foreach($oldFoods as $food)
{
$food->user_id = $user->id;
$food->save();
}
现在对于您的第三点,如果用户没有帖子,那么您可以做一个小检查,如下所示:
$user = User::find($request->id);
$posts = $user->posts()->get()->first();
if(isset($posts))
{
$user->delete();
}
else
{
$user->forceDelete();
}
希望这能满足您的所有需求。
结论 所以最后你可以在userController 中拥有你的destroy 方法:
public function destroy($id)
{
$user = User::findOrFail($id);
$foods = $user->food()->get();
if(isset($foods))
{
$botUser = User::where('username', '=', 'bot'); // Find the bot user
foreach($foods as $food)
{
$food->user_id = $botUser->id;
$food->save();
}
$user->delete();
}
else
{
$user->forceDelete();
}
Storage::delete($user->image);
return redirect()->route('users.index')->with('flash_message', 'User successfully deleted');
}