1<?php
2class Link extends Coupling{
3 protected $source;
4 protected $target;
5
6 function __construct(DynamicRecord $source, DynamicRecord $target, $table = NULL){
7 $this->source = $source;
8 $this->target = $target;
9 if (empty($table)) {
10 $table = $source->table.'2'.$target->table;
11 }
12 parent::__construct($source->table.'Id', $target->table.'Id', $table);
13 }
14
15 function selectTargets($sourceIds, $pageSize = 0, $pageNum = 0, $where = ''){
16 $sourceIds = (array) $sourceIds;
17 $query = "t.* FROM {$this->target->table} AS t, $this->table AS l
18 WHERE t.{$this->target->keyField} = l.$this->targetField
19 AND l.$this->sourceField IN " . self::getList($sourceIds);
20 if (!empty($where)) {
21 $query .= " AND " . $where;
22 }
23 $query .= self::getLimit($pageSize, $pageNum);
24 return $this->target->selectWith($query, $sourceIds);
25 }
26
27 function selectSources($targetIds, $pageSize = 0, $pageNum = 0, $where = ''){
28 $targetIds = (array) $targetIds;
29 $query = "s.* FROM {$this->source->table} AS s, $this->table AS l
30 WHERE s.{$this->source->keyField} = l.$this->sourceField
31 AND l.$this->targetField IN " . self::getList($targetIds);
32 if (!empty($where)) {
33 $query .= " AND " . $where;
34 }
35 $query .= self::getLimit($pageSize, $pageNum);
36 return $this->source->selectWith($query, $targetIds);
37 }
38
39 function selectMappedTargets($sourceIds, $pageSize = 0, $pageNum = 0, $where = ''){
40 $mappedTargetIds = $this->mapTargets($sourceIds, $pageSize, $pageNum, $where);
41 $idMap = array();
42 foreach ($mappedTargetIds as $targetIds) {
43 foreach ($targetIds as $targetId) {
44 $idMap[] = $targetId;
45 }
46 }
47 $objectMap = $this->target->resolve(array_unique($idMap));
48 $mappedObjects = array();
49 foreach ($mappedTargetIds as $sourceId => $targetIds) {
50 foreach ($targetIds as $targetId) {
51 $mappedObjects[$sourceId][] = $objectMap[$targetId];
52 }
53 }
54 return $mappedObjects;
55 }
56
57 function selectMappedSources($targetIds, $pageSize = 0, $pageNum = 0, $where = ''){
58 $mappedSourceIds = $this->mapSources($targetIds, $pageSize, $pageNum, $where);
59 $idMap = array();
60 foreach ($mappedSourceIds as $targetId => $sourceIds) {
61 foreach ($sourceIds as $sourceId) {
62 $idMap[] = $sourceId;
63 }
64 }
65 $objectMap = $this->source->resolve(array_unique($idMap));
66 $mappedObjects = array();
67 foreach ($mappedSourceIds as $targetId => $sourceIds) {
68 foreach ($sourceIds as $sourceId) {
69 $mappedObjects[$targetId][] = $objectMap[$sourceId];
70 }
71 }
72 return $mappedObjects;
73 }
74}