在我们的项目中,我们必须对每个帖子使用软删除。在laravel文档中,我认为我们只能将此功能用于表格。
我们可以将它用于桌面上的帖子,例如
$id = Contents::find( $id );
$id->softDeletes();
软删除模型时,实际上并未从数据库中删除它。而是在记录上设置deleted_at时间戳。要为模型启用软删除,请在模型上指定softDelete属性(Documentation):
例如(使用posts
表和Post
模型):
class Post extends Eloquent {
protected $table = 'posts';
protected $softDelete = true;
// ...
}
要向表中添加deleted_at列,可以使用迁移中的softDeletes方法:
例如(up
表的迁移类'posts
方法):
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function(Blueprint $table)
{
$table->increments('id');
// more fields
$table->softDeletes(); // <-- This will add a deleted_at field
$table->timeStamps();
});
}
现在,当您在模型上调用delete
方法时,deleted_at
列将设置为当前的timestamp
。查询使用软删除的模型时,“已删除”模型将不会包含在查询结果中。对soft delete
你可以使用的模型:
$model = Contents::find( $id );
$model->delete();
删除(软)模型由timestamp
识别,如果deleted_at
字段是NULL
,那么它不会被删除,并且使用restore
方法实际上使deleted_at
字段NULL
。要永久删除模型,请使用forceDelete
方法。
use Illuminate\Database\Eloquent\SoftDeletingTrait; // <-- This is required
class Post extends Eloquent {
use SoftDeletingTrait; // <-- Use This Insteaf Of protected $softDelete = true;
protected $table = 'posts';
// ...
}
use Illuminate\Database\Eloquent\SoftDeletes; // <-- This is required
class Post extends Eloquent {
use SoftDeletes; // <-- Use This Instead Of SoftDeletingTrait
protected $table = 'posts';
// ...
}
你实际上做了正常的删除。但是在模型上,您指定它是一个软删除模型。
所以在你的模型上添加代码:
class Contents extends Eloquent {
use SoftDeletingTrait;
protected $dates = ['deleted_at'];
}
然后在你的代码上做正常删除,如:
$id = Contents::find( $id );
$id ->delete();
还要确保你的桌子上有deleted_at
列。
只是Laravel 5的更新:
在Laravel 4.2中:
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class Post extends Eloquent {
use SoftDeletingTrait;
protected $dates = ['deleted_at'];
}
进入Laravel 5:
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model {
use SoftDeletes;
protected $dates = ['deleted_at'];
在Laravel 5.5 Soft Deleted作品(对我来说)。
数据库
deleted_at字段,默认为NULL值
模型
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model {
use SoftDeletes;
}
调节器
public function destroy($id)
{
User::find($id)->delete();
}
在最新版本的Laravel中,即Laravel 5.0之上。执行此任务非常简单。在Model中,只需编写'use SoftDeletes'即可。例
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model
{
use SoftDeletes;
}
在Controller中,您可以删除。例
User::where('email', '[email protected]')->delete();
要么
User::where('email', '[email protected]')->softDeletes();
确保用户表中必须包含“deleted_at”列。
以下是laravel.com的详细信息
http://laravel.com/docs/eloquent#soft-deleting
软删除模型时,实际上并未从数据库中删除它。而是在记录上设置deleted_at时间戳。要为模型启用软删除,请在模型上指定softDelete
属性:
class User extends Eloquent {
protected $softDelete = true;
}
要向表中添加deleted_at列,可以使用迁移中的softDeletes
方法:
$table->softDeletes();
现在,当您在模型上调用delete方法时,deleted_at列将设置为当前时间戳。查询使用软删除的模型时,“已删除”模型将不会包含在查询结果中。