向Larave软删除功能添加新列fromLast = TRUE
个小整数。
deleted_flag
模型的迁移
trait CustomSoftDeleteTrait
{
use SoftDeletes;
protected function runSoftDelete()
{
$query = $this->setKeysForSaveQuery($this->newModelQuery());
$time = $this->freshTimestamp();
$columns = [$this->getDeletedAtColumn() => $this->fromDateTime($time)];
$this->{$this->getDeletedAtColumn()} = $time;
if ($this->timestamps && ! is_null($this->getUpdatedAtColumn())) {
$this->{$this->getUpdatedAtColumn()} = $time;
$columns[$this->getUpdatedAtColumn()] = $this->fromDateTime($time);
}
$columns[$this->getDeletedFlagColumn()] = 1; //<-- here is the deleting
$query->update($columns);
}
protected function restore()
{
if ($this->fireModelEvent('restoring') === false) {
return false;
}
$this->{$this->getDeletedFlagColumn()} = 0; //<-- here is restoring
$this->{$this->getDeletedAtColumn()} = null;
$this->exists = true;
$result = $this->save();
$this->fireModelEvent('restored', false);
return $result;
}
public function getDeletedFlagColumn()
{
return defined('static::DELETED_FLAG') ? static::DELETED_FLAG : 'deleted_flag';
}
}
在模型中使用自定义特征,
Schema::create('families', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->integer('family_type');
$table->timestamp('create_date')->nullable();
$table->timestamp('update_date')->nullable();
$table->timestamp('delete_date')->nullable();
$table->tinyInteger('delete_flg')->nullable();
});
使用class Family extends Model
{
use CustomSoftDeleteTrait;
protected $guarded = [
'id',
];
const CREATED_AT = 'create_date';
const UPDATED_AT = 'update_date';
const DELETED_AT = 'delete_date';
const DELETED_FLAG = 'delete_flg';
}
删除模型时,同时设置了$family->delete()
和delete_date
列。恢复模型后,只有一个字段delete_flg
设置为null。 delete_date
字段保持为1。
答案 0 :(得分:0)
这是一个相当“棘手”的错误。
但是您要做的就是在自定义特征中将restore()函数的修改器从protected更改为public。
protected function restore() { /**/ }
应该变成
public function restore() { /**/ }
不能从您的家庭模型中访问受保护的功能。因此,PHP仅使用Eloquent Soft Delete Trait中的原始restore()方法。