Moving the relations to a dedicated Namespace

This commit is contained in:
2026-08-19 10:59:49 -03:00
parent 64bce1da47
commit 46dd177be9
7 changed files with 124 additions and 46 deletions
+75
View File
@@ -0,0 +1,75 @@
<?php
namespace ORM\Relations;
use ORM\DBInstance;
use ORM\Collection;
/**
* Belongs to Many
*
* Defines that this object is related to many other instances
* of other classes throw a pivot table.
*
* Table Post = (id, name, content)
* Table Tag = (id, name)
* Table Post_Tag = (id, postid, tagid)
*
* This relation will be created in both classes
*/
class BelongsToMany {
private $localObject;
private $foreignObject;
private $pivotTable;
private $localInPivot;
private $remoteInPivot;
private $remoteFilter;
private $remoteLimit;
/**
* Build the Connection
*
* @param mixed $localObject
* @param mixed $foreignObject
* @param mixed $pivotTable
* @param mixed $localInPivot
* @param mixed $remoteInPivot
* @param mixed $remoteFilter
* @param mixed $remoteLimit
*/
function __construct($localObject, $foreignObject, $pivotTable, $localInPivot, $remoteInPivot, $remoteFilter = Array(), $remoteLimit = Array()) {
$this->localObject = $localObject;
$this->foreignObject = $foreignObject;
$this->pivotTable = $pivotTable;
$this->localInPivot = $localInPivot;
$this->remoteInPivot = $remoteInPivot;
$this->remoteFilter = $remoteFilter;
$this->remoteLimit = $remoteLimit;
}
function get() : Collection {
$limitsSql = '';
foreach ($this->remoteLimit as $key => $value) {
$limitsSql .= "$key $value ";
}
$pivotTable = '{' . $this->pivotTable . '}';
$sql = "SELECT $this->remoteInPivot FROM $pivotTable WHERE $this->localInPivot = ? $limitsSql";
$relations = DBInstance::query($sql, Array($this->localObject->id), $this->localObject::_connectionName);
$ids = Array();
foreach ($relations as $relation) {
$ids[] = $relation->{$this->remoteInPivot};
}
if (empty($ids)) {
return new Collection();
}
return $this->foreignObject::findMany(array_merge(Array('id' => Array('IN', $ids)), $this->remoteFilter), Array('*'), $this->remoteLimit);
}
}