BelongsToManyExtended.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace ORM;
  3. class BelongsToManyExtended {
  4. private $localObject;
  5. private $foreignObject;
  6. private $pivotTable;
  7. private $localInPivot;
  8. private $remoteInPivot;
  9. private $remoteFilter;
  10. private $remoteLimit;
  11. private $softDelete;
  12. function __construct($localObject, $foreignObject, $pivotTable, $localInPivot, $remoteInPivot, $remoteFilter = Array(), $remoteLimit = Array(), $softDelete) {
  13. $this->localObject = $localObject;
  14. $this->foreignObject = $foreignObject;
  15. $this->pivotTable = $pivotTable;
  16. $this->localInPivot = $localInPivot;
  17. $this->remoteInPivot = $remoteInPivot;
  18. $this->remoteFilter = $remoteFilter;
  19. $this->remoteLimit = $remoteLimit;
  20. $this->softDelete = $softDelete;
  21. }
  22. function get() : Collection {
  23. $limitsSql = '';
  24. foreach ($this->remoteLimit as $key => $value) {
  25. $limitsSql .= "$key $value ";
  26. }
  27. $pivotTable = '{' . $this->pivotTable . '}';
  28. $sql = '';
  29. if($this->softDelete){
  30. $sql = "SELECT * FROM $pivotTable WHERE $this->localInPivot = ? AND deleted_at IS NULL $limitsSql";
  31. } else {
  32. $sql = "SELECT * FROM $pivotTable WHERE $this->localInPivot = ? $limitsSql";
  33. }
  34. $relations = DBInstance::query($sql, Array($this->localObject->id), $this->localObject::_connectionName);
  35. $objects = new Collection();
  36. if (empty($relations)) {
  37. return new Collection();
  38. }
  39. foreach ($relations as $relation) {
  40. $relation->childElement = $this->foreignObject::findOne(array_merge(Array("id" => Array("=", $relation->{$this->remoteInPivot})), $this->remoteFilter));
  41. $objects[] = $relation;
  42. }
  43. if (empty($objects)) {
  44. return new Collection();
  45. }
  46. return $objects;
  47. }
  48. }