在我们的项目中,我们必须对每个帖子使用软删除。在 laravel 文档中,我认为我们只能将此功能用于表格。
我们可以将它用于 table 上的帖子吗,例如
$id = Contents::find($id);
$id->softDeletes();
最佳答案
更新版本(Version 5.0 & Later):
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model {
use SoftDeletes;
protected $table = 'posts';
// ...
}
When soft deleting a model, it is not actually removed from your database. Instead, a
deleted_at
timestamp is set on the record. To enable soft deletes for a model, specify thesoftDelete
property on the model (Documentation).
对于 ( Version 4.2 ):
use Illuminate\Database\Eloquent\SoftDeletingTrait; // <-- This is required
class Post extends Eloquent {
use SoftDeletingTrait;
protected $table = 'posts';
// ...
}
4.2 版之前(但不是 4.2 及更高版本)
例如(使用posts
表和Post
模型):
class Post extends Eloquent {
protected $table = 'posts';
protected $softDelete = true;
// ...
}
To add a deleted_at column to your table, you may use the
softDeletes
method from a migration:
例如(posts
表的迁移类的up
方法):
/**
* 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
列将设置为当前时间戳
。当查询使用软删除的模型时,“删除”的模型将不会包含在查询结果中。要软删除
您可能使用的模型:
$model = Contents::find( $id );
$model->delete();
删除的(软)模型由 timestamp
标识,如果 deleted_at
字段为 NULL
则它不会被删除并使用 restore
方法实际上使 deleted_at
字段 NULL
。要永久删除模型,您可以使用 forceDelete
方法。
关于php - Laravel 软删除帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22426165/