在 Laravel 中使用自定义软删除列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42049726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:16:14  来源:igfitidea点击:

Use custom soft deleted column in laravel

phplaravellaravel-5.3

提问by A.B.Developer

I know that How can I use Soft Deleting feature for models in laravel. like this :

我知道如何对 Laravel 中的模型使用软删除功能。像这样 :

class Flight extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];
}

But I want to use a custom column named sender_deleted_atfor that feature where all related methods like forceDelete, restore, withTrashedand etc work based that column.

但我想使用以sender_deleted_at该功能命名的自定义列,其中所有相关方法(如forceDeleterestorewithTrashed等)都基于该列工作。

I wrote this QuestionBut I could not get the right answer.

我写了这个问题但我无法得到正确的答案。

I'm using Laravel 5.3.

我正在使用 Laravel 5.3。

回答by apokryfos

The SoftDeletes trait uses this code to "delete" a row:

SoftDeletes 特性使用此代码“删除”一行:

protected function runSoftDelete() {
        $query = $this->newQueryWithoutScopes()->where($this->getKeyName(), $this->getKey());
        $this->{$this->getDeletedAtColumn()} = $time = $this->freshTimestamp();
        $query->update([$this->getDeletedAtColumn() => $this->fromDateTime($time)]);
}

The body of getDeletedAtColumn()is:

的身体getDeletedAtColumn()是:

public function getDeletedAtColumn() {
    return defined('static::DELETED_AT') ? static::DELETED_AT : 'deleted_at';
}

Therefore you can do this:

因此,您可以这样做:

class Flight extends Model
{
    use SoftDeletes;    
    protected $dates = ['my_deleted_at'];
    const DELETED_AT = 'my_deleted_at';
}

回答by rummykhan

Short Answer:Just declare a const DELETED_ATin your model and give it a column name you want to use.

简短回答:只需const DELETED_AT在您的模型中声明 a并为其指定一个您要使用的列名。

<?php

namespace App;

use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use SoftDeletes;

    use Notifiable;

    const DELETED_AT = 'deletedAt';
}

Explanation:Well if you look at method getDeletedAtColumnin trait Illuminate\Database\Eloquent\SoftDeletes

说明:那么,如果你看一下方法getDeletedAtColumntrait Illuminate\Database\Eloquent\SoftDeletes

/**
 * Get the name of the "deleted at" column.
 *
 * @return string
 */
public function getDeletedAtColumn()
{
    return defined('static::DELETED_AT') ? static::DELETED_AT : 'deleted_at';
}

It's actually checking if you've declared a constant name DELETED_ATin your implementing class than get that value and if you haven't simply use deleted_atas a soft delete column.

它实际上是检查您是否DELETED_AT在实现类中声明了一个常量名称而不是获取该值,以及您是否没有简单地deleted_at用作软删除列。