1: <?php
2:
3: namespace Alchemy\orm;
4: use Alchemy\core\schema\Column;
5: use Alchemy\core\query\ColumnRef;
6: use Alchemy\core\query\TableRef;
7: use Exception;
8:
9:
10: 11: 12: 13:
14: class RelatedSet {
15: private $owner;
16: private $relationship;
17:
18:
19: 20: 21: 22: 23: 24:
25: public function __construct(DataMapper $owner, Relationship $relationship) {
26: $this->owner = $owner;
27: $this->relationship = $relationship;
28: }
29:
30:
31: 32: 33:
34: public function __call($name, $args) {
35: if (method_exists($this->relationship, $name)) {
36: array_unshift($args, $this->owner);
37: return call_user_func_array(array($this->relationship, $name), $args);
38: }
39:
40: throw new \Exception("Relationship::{$this->getType()} does not have a method {$name}()");
41: }
42:
43:
44: public function select() {
45: if (!($session = $this->owner->getSession())) {
46: throw new \Exception("Object must belong to session for relationship queries");
47: }
48:
49: $query = new SessionSelect($session, $this->getDestinationClass());
50: $map = $this->relationship->getRemoteColumnMap($this->owner);
51: return $query->where($query->table()->equal($map));
52: }
53:
54:
55: public function all() {
56: return $this->select()->all();
57: }
58:
59:
60: public function one() {
61: return $this->select()->one();
62: }
63:
64:
65: public function first() {
66: if (!($session = $this->owner->getSession())) {
67: throw new Exception("Object must belong to session for relationship queries");
68: }
69:
70:
71: if ($this->relationship->isSingleObject()) {
72: $map = $this->relationship->getRemoteColumnMap($this->owner);
73: $obj = $session->object($this->getDestinationClass(), $map);
74:
75: if ($obj) {
76: return $obj;
77: }
78: }
79:
80:
81: return $this->select()->first();
82: }
83: }
84: