ApiSoftDeletes.php 2.4 KB

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