ApiSoftDeletes.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace App\Base\Models;
  3. use Illuminate\Database\Eloquent\SoftDeletes;
  4. trait ApiSoftDeletes
  5. {
  6. use SoftDeletes ;
  7. public static function bootSoftDeletes()
  8. {
  9. static::addGlobalScope(new ApiSoftDeletingScope);
  10. }
  11. /**
  12. * Determine if the model instance has been soft-deleted.
  13. *
  14. * @return bool
  15. */
  16. public function trashed()
  17. {
  18. return $this->{$this->getDeletedAtColumn()} == static::STATUS_DELETED;
  19. }
  20. /**
  21. * Perform the actual delete query on this model instance.
  22. *
  23. * @return void
  24. */
  25. protected function runSoftDelete()
  26. {
  27. $query = $this->newQueryWithoutScopes()->where($this->getKeyName(), $this->getKey());
  28. $this->{$this->getDeletedAtColumn()} = $this->getDeletedColumnValue();
  29. $query->update([$this->getDeletedAtColumn() => $this->getDeletedColumnValue()]);
  30. }
  31. /**
  32. * Restore a soft-deleted model instance.
  33. *
  34. * @return bool|null
  35. */
  36. public function restore()
  37. {
  38. // If the restoring event does not return false, we will proceed with this
  39. // restore operation. Otherwise, we bail out so the developer will stop
  40. // the restore totally. We will clear the deleted timestamp and save.
  41. if ($this->fireModelEvent('restoring') === false) {
  42. return false;
  43. }
  44. $this->{$this->getDeletedAtColumn()} = static::STATUS_ENABLED;
  45. // Once we have saved the model, we will fire the "restored" event so this
  46. // developer will do anything they need to after a restore operation is
  47. // totally finished. Then we will return the result of the save call.
  48. $this->exists = true;
  49. $result = $this->save();
  50. $this->fireModelEvent('restored', false);
  51. return $result;
  52. }
  53. /**
  54. * 获取删除字段值
  55. * @return string|int
  56. */
  57. public function getDeletedColumnValue(){
  58. return self::STATUS_DELETED;
  59. }
  60. /**
  61. * Get the fully qualified "deleted at" column.
  62. *
  63. * @return string
  64. */
  65. public function getQualifiedDeletedAtColumn()
  66. {
  67. $alias = empty($this->getAliasName())?$this->getTable():$this->getAliasName();
  68. return $alias.'.'.$this->getDeletedAtColumn();
  69. }
  70. /**
  71. * 该方法纯粹为了覆盖SoftDeletes里面指定delete_at类型不正确的问题
  72. */
  73. public function initializeSoftDeletes()
  74. {
  75. }
  76. }