65fb833f77f9f19b358ca64f8c93e03b10fb613a
[mdref/mdref-pq-gateway] / Relations.md
1 # class pq\Gateway\Table\Relations implements Countable, IteratorAggregate
2
3 Retrieve any relations referenced by the table through foreign keys.
4 See pq\Gateway\Table::by() and pq\Gateway\Table::with().
5
6 ## Query:
7
8 The following query is executed by the current executor of the table to retrieve the table references:
9
10 select
11 case when att1.attname like '%\_'||att2.attname then
12 substring(att1.attname from '^.*(?=_'||att2.attname||'$)')
13 else
14 att1.attname
15 end as "id"
16 ,cl1.relname as "foreignTable"
17 ,att1.attname as "foreignColumn"
18 ,cl2.relname as "referencedTable"
19 ,att2.attname as "referencedColumn"
20 from
21 pg_constraint co
22 ,pg_class cl1
23 ,pg_class cl2
24 ,pg_attribute att1
25 ,pg_attribute att2
26 where
27 ( cl1.relname = \$1
28 or cl2.relname = \$1)
29 and co.confrelid != 0
30 and co.conrelid = cl1.oid
31 and co.conkey[1] = att1.attnum and cl1.oid = att1.attrelid
32 and co.confrelid = cl2.oid
33 and co.confkey[1] = att2.attnum and cl2.oid = att2.attrelid
34 order by
35 cl1.relname
36 ,att1.attnum
37
38 ## Cache:
39
40 The result of this query is cached in the metadata cache under the following key, where $table is converted to a string by pq\Gateway\Table::__toString():
41
42 "$table:relations"
43
44 ## Foreign key access:
45
46 Relations can be accessed as virtual properties or through pq\Gateway\Table\Relations::getReference().
47
48 <?php
49
50 use pq\Gateway\Table;
51
52 $relations = new Table\Relations(new Table("account_email"));
53
54 // $relations->reference->account
55 $account_rel = $relations->getReference("account");
56 $account_rel = $relations->account;
57
58 ?>
59
60 > ***NOTE:***
61 The relation name is the column name of the foreign key with the column name of the referenced column cut off the end.
62
63 ## Properties:
64
65 * protected array $references
66 The table's foreign keys.
67