php - Laravel 软删除帖子

标签 php laravel laravel-4

在我们的项目中,我们必须对每个帖子使用软删除。在 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 the softDelete 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/

相关文章:

php - Laravel 测试 DatabaseMigrations 未运行所有迁移

javascript - 如何在 CRUD 执行后改进/保持分页

拉拉维尔 4 : php artisan down not defined

php - 我在 PHP 中使用 try 但 PDO 不会捕获异常

php - mySQL:将一列的结果作为多列返回

php - Laravel 删除多个复选框

apache - laravel 在此服务器上找不到请求的 url

javascript - Angular JS with Laravel -- 如何绑定(bind) Eloquent ORM 数组来查看

php - 不能在此查询中使用 mysql count

php - PHP中两个日期的总和