76 lines
2.2 KiB
PHP
76 lines
2.2 KiB
PHP
<?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);
|
|
}
|
|
|
|
}
|