📜  deleted_at - PHP (1)

📅  最后修改于: 2023-12-03 14:40:42.106000             🧑  作者: Mango

deleted_at - PHP

The deleted_at field is a common feature in database design where it acts as a soft delete mechanism. Instead of physically deleting a record, it is simply marked as deleted by setting the deleted_at timestamp field to the current timestamp. This allows for easy recovery of deleted data and history tracking of changes.

In PHP, using the deleted_at field is quite easy. When querying for data, simply filter out any rows where the deleted_at field is not null.

// Query all users that have not been deleted
$users = DB::table('users')
                ->where('deleted_at', null)
                ->get();

When deleting a record, instead of issuing a DELETE query, update the deleted_at field with the current timestamp.

// Soft delete user
$user = User::find($id);
$user->deleted_at = now();
$user->save();

To restore a soft deleted record, simply set the deleted_at field back to null.

// Restore soft deleted user
$user = User::withTrashed()->find($id);
$user->deleted_at = null;
$user->save();

Overall, using the deleted_at field provides a flexible and powerful mechanism for managing deleted data in PHP applications.