SoftDeleteBehavior.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. namespace common\behaviors;
  3. use yii\base\Behavior;
  4. use yii\base\Event;
  5. use yii\db\BaseActiveRecord;
  6. use yii\db\Expression;
  7. use common\models\base\BaseModel;
  8. /**
  9. * 伪删除行为
  10. *
  11. * Class SoftDeleteBehavior
  12. * @package common\behaviors
  13. * @author jianyan74 <751393839@qq.com>
  14. */
  15. class SoftDeleteBehavior extends Behavior
  16. {
  17. /**
  18. * @var string SoftDelete attribute
  19. */
  20. public $attribute = 'status';
  21. /**
  22. * @var callable|Expression The expression that will be used for generating the -1.
  23. * This can be either an anonymous function that returns the -1 value,
  24. * or an [[Expression]] object representing a DB expression (e.g. `-1`).
  25. * If not set, it will use the value of `-1` to set the attributes.
  26. */
  27. public $value;
  28. /**
  29. * @inheritdoc
  30. */
  31. // public function events()
  32. // {
  33. // return [BaseActiveRecord::EVENT_BEFORE_DELETE => 'softDeleteEvent'];
  34. // }
  35. /**
  36. * Set the attribute with the current -1 to mark as deleted
  37. *
  38. * @param Event $event
  39. */
  40. public function softDeleteEvent($event)
  41. {
  42. // remove and mark as invalid to prevent real deletion
  43. $this->softDelete();
  44. $event->isValid = false;
  45. }
  46. /**
  47. * 伪删除
  48. */
  49. public function softDelete()
  50. {
  51. // set attribute with evaluated 1
  52. $attribute = $this->attribute;
  53. $this->owner->$attribute = $this->getValue(null);
  54. // save record
  55. return $this->owner->save(false, [$attribute]);
  56. }
  57. /**
  58. * 取消删除
  59. */
  60. public function unDelete()
  61. {
  62. // set attribute as 1
  63. $attribute = $this->attribute;
  64. $this->owner->$attribute = 1;
  65. // save record
  66. return $this->owner->save(false, [$attribute]);
  67. }
  68. /**
  69. * 直接删除
  70. *
  71. * Delete record from database regardless of the $safeMode attribute
  72. */
  73. public function hardDelete()
  74. {
  75. // store model so that we can detach the behavior
  76. /** @var BaseModel $model */
  77. $model = $this->owner;
  78. $this->detach();
  79. // delete as normal
  80. return 0 !== $model->delete();
  81. }
  82. /**
  83. * Evaluate the -1 to be saved.
  84. *
  85. * @param Event|null $event the event that triggers the current attribute updating.
  86. * @return mixed the attribute value
  87. */
  88. protected function getValue($event)
  89. {
  90. if ($this->value instanceof Expression) {
  91. return $this->value;
  92. } else {
  93. return $this->value !== null ? call_user_func($this->value, $event) : -1;
  94. }
  95. }
  96. }
粤ICP备19079148号