Linux删除软链:Laravel软删除帖子

在我们的项目中,我们必须为每个帖子使用软删除。在 laravel 文档中,我认为我们只能将此功能用于表。

我们可以将其用于表格上的帖子,例如

$id = Contents::find($id);
$id->softDeletes();
119

更新版本 (Version 5.0 & Later):

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model {
    use SoftDeletes;
    protected $table = 'posts';
    // ...
}

软删除模型时,实际上不会将其从数据库中删除。而是在记录上设置deleted_at时间戳。要启用模型的软删除,请在模型上指定softDelete属性 (Documentation)。

For (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;
    
    // ...
}

要将deleted_at列添加到表中,可以使用迁移中的softDeletes方法:

例如(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列将被设置为当前的timestamp。当查询使用软删除的模型时,“已删除”的模型将不包括在查询结果中。对于soft delete您可以使用的模型:

$model = Contents::find( $id );
$model->delete();

删除的(软)模型由timestamp标识,如果deleted_at字段为NULL,则不会删除它,使用restore方法实际上会生成deleted_at字段NULL。要永久删除模型,可以使用forceDelete方法。

25

您实际上执行正常删除。但是在模型上,您指定它是一个 softdelete 模型。

所以在你的模型中添加代码:

class Contents extends Eloquent {
    use SoftDeletingTrait;
    protected $dates = ['deleted_at'];
}

然后在你的代码做正常删除像:

$id = Contents::find( $id );
$id ->delete();

还要确保你的表上有deleted_at列。

或者只看文档:http://laravel.com/docs/eloquent#soft-deleting

10

我刚刚用 Laravel 8 做到了这一点,它工作了。这基本上是 @ The alpha 所说的,但试图更快地包装所有内容。按照以下步骤操作。

迁移文件中添加:

$table->softDeletes();

模型中:

use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model
{
    use SoftDeletes;
    ...
];

}

控制器中:

$user->delete();

奖励:如果您需要恢复已删除的用户

User::withTrashed()->find($id);->restore();
6

只是 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'];

本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处

(300)
第十三届蓝桥杯web应用开发:使用WordPress开发Web应用程序
上一篇
Startup.xls:从 xlsimportrange
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(12条)