首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Laravel:正确覆盖SoftDeletes特征

Laravel:正确覆盖SoftDeletes特征
EN

Stack Overflow用户
提问于 2018-06-01 16:51:11
回答 1查看 2.6K关注 0票数 3

我想创建一个使用名为SoftDeletesWithStatusSoftDeletes的特征,该特征还将更新状态列。我的问题是我想在SoftDeletes的函数中间实现我的代码,就像这样:

代码语言:javascript
复制
protected function runSoftDelete() {
    $query = $this->newQueryWithoutScopes()->where($this->getKeyName(), $this->getKey());
    $time = $this->freshTimestamp();
    $columns = [$this->getDeletedAtColumn() => $this->fromDateTime($time)];

   //I want to implement my code here

    $this->{$this->getDeletedAtColumn()} = $time;
    if ($this->timestamps && ! is_null($this->getUpdatedAtColumn())) {
        $this->{$this->getUpdatedAtColumn()} = $time;
        $columns[$this->getUpdatedAtColumn()] = $this->fromDateTime($time);
    }
    $query->update($columns);
}

public function restore() {
    if ($this->fireModelEvent('restoring') === false) {
        return false;
    }
    $this->{$this->getDeletedAtColumn()} = null;

    //I want to implement my code here

    $this->exists = true;
    $result = $this->save();
    $this->fireModelEvent('restored', false);
    return $result;
}

将代码复制粘贴到我的SoftDeletesWithStatus特征中并在其中实现代码是更好的解决方案吗?

谢谢你的帮助。

EN

回答 1

Stack Overflow用户

发布于 2018-06-01 17:18:26

我最接近的解决方案是:

代码语言:javascript
复制
<?php
namespace App;

use Illuminate\Database\Eloquent\SoftDeletes;

//Status 1 = Activated; Status 99 = Deleted
trait SoftDeletesWithStatus {
    use SoftDeletes {
        SoftDeletes::runSoftDelete as parentRunSoftDelete;
        SoftDeletes::restore as parentRestore;
    }

    public function getStatusColumn() {
        return defined('static::STATUS') ? static::STATUS : 'status';
    }

    public function runSoftDelete() {
        $this->parentRunSoftDelete();
        $query = $this->newQueryWithoutScopes()->where($this->getKeyName(), $this->getKey());
        $columns = [$this->getStatusColumn() => 99];
        $this->{$this->getDeletedAtColumn()} = 99;
        $query->update($columns);
    }

    public function restore() {
        $result = $this->parentRestore();
        $this->{$this->getStatusColumn()} = 1;
        $this->save();
        return $result;
    }
}

然后我简单地在我想要的模型中使用我的特征:

代码语言:javascript
复制
<?php
namespace App;

use Illuminate\Database\Eloquent\Model;
use App\SoftDeletesWithStatus;

class MyModel extends Model {
    use SoftDeletesWithStatus;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50639559

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档