flush
[mdref/mdref-pq-gateway] / pq-gateway / pq / Gateway / Table / getRelations.md
1 # \pq\Gateway\Table\Relations|stdClass pq\Gateway\Table::getRelations([string $to = NULL])
2
3 Get the relations (by foreign key) of this table.
4 See pq\Gateway\Table::hasRelation().
5
6 > ***NOTE:***
7 The relation name is the column name of the foreign key with the column name of the referenced column cut off the end.
8
9 ## Params:
10
11 * Optional string $to = NULL
12 The table name of which to get the relation to.
13
14 ## Returns:
15
16 * stdClass, if $to is given and a relation exists.
17 * NULL, if $to is given and a relation does not exist.
18 * pq\Gateway\Table\Relations, all relations if $to is omitted.
19
20 ## Example:
21
22 <?php
23
24 use pq\Gateway\Table;
25
26 $conn = new pq\Connection;
27 $conn->exec("
28 drop table if exists reftable cascade;
29 -- drop table if exists account cascade;
30 -- drop table if exists account_email cascade;
31
32 -- create table account (
33 -- id uuid default uuid_generate_v4() primary key,
34 -- password char(60),
35 -- name varchar(68)
36 -- );
37
38 -- create table account_email (
39 -- account_id uuid not null references account(id) on delete cascade,
40 -- email varchar(255) not null unique,
41 -- primary key (account_id, email)
42 -- );
43
44 create table reftable (
45 id serial primary key,
46 my_account integer references account(id),
47 account_id integer references account(id),
48 second_account_id integer references account(id),
49 email integer references account_email(email)
50 );
51 ");
52
53 $fgn_table = new Table("reftable");
54 var_dump($fgn_table->getRelations());
55
56 ?>
57
58 Yields:
59
60 object(pq\Gateway\Table\Relations)#10 (1) {
61 ["references":protected]=>
62 object(stdClass)#17 (4) {
63 ["my_account"]=>
64 object(stdClass)#18 (1) {
65 ["reftable"]=>
66 object(stdClass)#19 (4) {
67 ["foreignTable"]=>
68 string(8) "reftable"
69 ["foreignColumn"]=>
70 string(10) "my_account"
71 ["referencedTable"]=>
72 string(7) "account"
73 ["referencedColumn"]=>
74 string(2) "id"
75 }
76 }
77 ["account"]=>
78 object(stdClass)#20 (1) {
79 ["reftable"]=>
80 object(stdClass)#21 (4) {
81 ["foreignTable"]=>
82 string(8) "reftable"
83 ["foreignColumn"]=>
84 string(10) "account_id"
85 ["referencedTable"]=>
86 string(7) "account"
87 ["referencedColumn"]=>
88 string(2) "id"
89 }
90 }
91 ["second_account"]=>
92 object(stdClass)#22 (1) {
93 ["reftable"]=>
94 object(stdClass)#23 (4) {
95 ["foreignTable"]=>
96 string(8) "reftable"
97 ["foreignColumn"]=>
98 string(17) "second_account_id"
99 ["referencedTable"]=>
100 string(7) "account"
101 ["referencedColumn"]=>
102 string(2) "id"
103 }
104 }
105 ["email"]=>
106 object(stdClass)#24 (1) {
107 ["reftable"]=>
108 object(stdClass)#25 (4) {
109 ["foreignTable"]=>
110 string(8) "reftable"
111 ["foreignColumn"]=>
112 string(5) "email"
113 ["referencedTable"]=>
114 string(13) "account_email"
115 ["referencedColumn"]=>
116 string(5) "email"
117 }
118 }
119 }
120 }