在 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
Use custom soft deleted column in laravel
提问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_at
for that feature where all related methods like forceDelete
, restore
, withTrashed
and etc work based that column.
但我想使用以sender_deleted_at
该功能命名的自定义列,其中所有相关方法(如forceDelete
、restore
、withTrashed
等)都基于该列工作。
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_AT
in 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 getDeletedAtColumn
in trait Illuminate\Database\Eloquent\SoftDeletes
说明:那么,如果你看一下方法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';
}
It's actually checking if you've declared a constant name DELETED_AT
in your implementing class than get that value and if you haven't simply use deleted_at
as a soft delete column.
它实际上是检查您是否DELETED_AT
在实现类中声明了一个常量名称而不是获取该值,以及您是否没有简单地deleted_at
用作软删除列。