我想创建一个使用名为SoftDeletesWithStatus
的SoftDeletes
的特征,该特征还将更新状态列。我的问题是我想在SoftDeletes
的函数中间实现我的代码,就像这样:
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
特征中并在其中实现代码是更好的解决方案吗?
谢谢你的帮助。
发布于 2018-06-01 17:18:26
我最接近的解决方案是:
<?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;
}
}
然后我简单地在我想要的模型中使用我的特征:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\SoftDeletesWithStatus;
class MyModel extends Model {
use SoftDeletesWithStatus;
}
https://stackoverflow.com/questions/50639559
复制相似问题