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

时间:2017-02-05 07:51:45

标签: php laravel laravel-5.3

我知道如何在laravel模型中使用Soft Deleting功能。像这样:

class Flight extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];
}

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

我写了this Question但我无法得到正确答案。

我使用的是Laravel 5.3。

2 个答案:

答案 0 :(得分:18)

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)]);
}

getDeletedAtColumn()的正文是:

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

因此你可以这样做:

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

答案 1 :(得分:6)

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

<?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';
}

说明:如果您查看getDeletedAtColumn中的方法trait 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';
}

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