UploadBehaviorTrait.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace common\modules\attachment\behaviors;
  3. use common\modules\attachment\models\Attachment;
  4. use common\modules\attachment\models\AttachmentIndex;
  5. use common\traits\EntityTrait;
  6. use yii\helpers\ArrayHelper;
  7. trait UploadBehaviorTrait
  8. {
  9. use EntityTrait;
  10. /**
  11. * 里面三段代码的顺序不能错..
  12. */
  13. public function afterDelete()
  14. {
  15. $relatedIds = $this->getRelatedIds();
  16. AttachmentIndex::deleteAll([
  17. 'entity_id' => $this->getEntityId(),
  18. 'entity' => $this->getEntity(),
  19. ]);
  20. foreach ($relatedIds as $id) {
  21. $this->deleteFile($id);
  22. }
  23. }
  24. public function deleteNotExistFiles($relatedIds, $existIds)
  25. {
  26. foreach (array_diff($relatedIds, $existIds) as $id) {
  27. // 删除索引关系
  28. AttachmentIndex::deleteAll([
  29. 'attachment_id' => $id,
  30. 'entity_id' => $this->getEntityId(),
  31. 'attribute' => $this->attribute,
  32. 'entity' => $this->getEntity(),
  33. ]);
  34. // 尝试删除文件
  35. $this->deleteFile($id);
  36. }
  37. }
  38. /**
  39. * 先检查文件是否被使用没有使用则删除,在beforedelete中
  40. * 尝试删除文件.
  41. *
  42. * @param integer $id
  43. * @return bool
  44. */
  45. public function deleteFile($id)
  46. {
  47. $isUse = AttachmentIndex::find()->where([
  48. 'attachment_id' => $id,
  49. ])->count();
  50. if ($isUse > 0) {
  51. return false;
  52. }
  53. $file = Attachment::findOne([
  54. 'id' => $id,
  55. ]);
  56. if ($file !== null) {
  57. //暂不删,不是所有附件都用到了这个
  58. // $file->delete();
  59. }
  60. }
  61. public function getRelatedIds()
  62. {
  63. $attachments = AttachmentIndex::find()->where([
  64. 'entity' => $this->getEntity(),
  65. 'entity_id' => $this->getEntityId(),
  66. 'attribute' => $this->attribute,
  67. ])->all();
  68. return ArrayHelper::getColumn($attachments, 'attachment_id');
  69. }
  70. public function saveIndex($id)
  71. {
  72. $relation = new AttachmentIndex();
  73. $relation->entity = $this->getEntity();
  74. $relation->entity_id = $this->getEntityId();
  75. $relation->attribute = $this->attribute;
  76. $relation->attachment_id = $id;
  77. $relation->save();
  78. }
  79. }