Laravel数据删除以及软删除的操作方法
所谓软删除就是逻辑删除,当然还有物理删除,逻辑删除指的是数据表记录并未真的从数据库删除,而是将表记录的标识状态标记为软删除,这样在查询的时候就可以加以过滤,让对应表记录看上去是被删除了。
Laravel中使用了一个日期字段作为标识状态,这个日期字段可以自定义,这里我们使用deleted_at,如果对应模型被软删除,则deleted_at字段的值为删除时间,否则该值为空。
-
1、删除模型
//1、第一种方法
Post::find(5)->delete();
//2、第二种方法
Post::destroy(5)
//3、第三种方法
Post::where('views', 0)->delete();
-
2、软删除
数据库中添加deleted_at字段
Model中使用SoftDeletes,具体可参考源码Illuminate\Database\Eloquent\SoftDeletes
...
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
...
按照1中常规的方法删除即可就被软删除了,find,get,all都将无法查找这些些被软删除后的数据
-
3、软删除查询
需要在普通的查询前调用withTrashed
Post::withTrashed()->find('1');
Post::withTrashed()->where('id','>',1)->get();
Post::withTrashed()->all();
-
4、软删除恢复
//恢复单个
Post::withTrashed()->find(1)->restore();
//恢复多个模型
Post::withTrashed()->where('id','>',1)->restore();
//恢复所有模型
Post::withTrashed()->restore();
-
5、强制删除
//删除单个
Post::withTrashed()->find(1)->forceDelete();
//删除多个模型
Post::withTrashed()->where('id','>',1)->forceDelete();
//删除所有模型
Post::withTrashed()->forceDelete();
-
6、关联模型
数据被软删除后关联的数据还想关联到该数据,需要在belongsTo后面加withTrashed
public function user()
{
return $this->belongsTo('App\User')->withTrashed();
}
Mac OS使用brew安装Nginx、MySQL、PHP-FPM的LAMP环境 Laravel 5.4 支持多个邮箱和Mail Driver并能够任意切换队列发送的方法
The whole experience felt smooth and convenient, especially with how easy it was to compare different options. The transparency around the best price for tadalafil made the decision feel simple and stress‑free. Everything worked reliably and left me with a very positive impression.
I have been absent for some time, but now I remember why I used to love this web site. Thanks, I’ll try and check back more frequently. How frequently you update your web site?
These are in fact fantastic ideas in concerning blogging. You have touched some nice factors here. Any way keep up wrinting.
There’s certainly a great deal to find out about this topic. I really like all of the points you’ve made.
Reading your article helped me a lot and I agree with you. But I still have some doubts, can you clarify for me? I’ll keep an eye out for your answers. https://www.gate.io/share/XwNAUwgM
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.