Subversion-Projekte lars-tiefland.prado

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
1 lars 1
<com:TContent ID="body" >
2
<!-- $Id $ -->
3
<h1 id="138046">Rekord Aktywny (ang. Active Record)</h1>
4
<com:SinceVersion Version="3.1a" />
5
<p id="690478" class="block-content">Rekordy Aktywne są obiektami, które opakowują wiersz w bazie danych lub widoku,
6
    obudowują (ang. encapsulate) dostęp do bazy danych oraz dziedziny logiki dla tych danych.
7
    Podstawą Rekordu Aktywnego są klasy biznesowe np. klasa
8
    <tt>Produkty</tt>, które są bardzo podobne do struktury rekordu należącego do bazy danych. Każdy Rekord Aktywny jest odpowiedzialny
9
    za zapisywanie i łądowanie danych do i z bazy danych.</p>
10
<div class="info"><b class="note">Info:</b>
11
    Struktura danych Rekordu Sktywnego powinna zgadzać się ze strukturą tablicy w bazie danych.
12
    Każda kolumna w bazie danych powinna posiadać odpowiadający element: zmienną lub właściwość w klasie Rekordu Aktywnego reprezentującego tablicę.
13
</div>
14
 
15
<h2 id="138047">Kiedy używać?</h2>
16
    <p id="690479" class="block-content">Rekord Aktywne jest dobrym wyborem dla dziedziny logiki, która nie jest zbyt złożona, tak jak tworzenie, odczyty, aktualizacje oraz usuwanie.
17
    Pochocne (ang. derivations) oraz sprawdzenia bazujące na pojedyńczym rekordzie sprawdzają się dobrze w tej konstrukcji.
18
    Rekord Aktywne ma podstawową zaletę, którą jest prostota. Łatwo jest stworzyć Rekord Aktywny, łatwo go również zrozuieć.
19
    </p>
20
 
21
    <p id="690480" class="block-content">Jednakże, jeśli twoja logika biznesowa staje się coraz bardziej złożona, wkrótce będziesz chciał
22
    używać bezpośrednich relacji, zbiorów, dziedziczenia twojego obiektu i tak dalej. Nie da się tego łatwo odwzorować za pomocą Rekordu Aktywnego,
23
    a dodawanie ich po kawałku staje się bardzo kłopotliwe. Innym argumentem przeciw Rekordowi Aktywnemu jest fakt, że łączy model obiektowy z modelem baz danych.
24
    To czyni trudniejszym refaktoring, gdy projekt idzie naprzód.
25
    </p>
26
 
27
    <p id="690481" class="block-content">Alternatywą jest używanie wzorca Data Mapper (mapa danych), który odseparowuje role obiektu biznesowego od tego jak te obiekty są przechowywane.
28
    Prado dostarcza
29
    Prado provides a darmowy wybór pomiędzy rekordem aktywnym a <a href="?page=Database.SqlMap">SqlMap Data Mapper</a>.
30
    SqlMap Data Mapper może być uzywany do wczytania obiektów Rekordu Aktywnego, i na odwrót, te Rekordy Aktywne mogą zostać użyte do aktualizacji bazy danych.
31
    Związek pomiędzy Rekordem Aktywnym a <a href="?page=Database.SqlMap">SqlMap</a> przedstawiony jest na kolejnym diagramie. Więcej informacji związanych z SqlMap Data Mapper można znaleźć w
32
    <a href="http://www.pradosoft.com/demos/sqlmap/">manualu SqlMap</a>.
33
    <img src=<%~ sqlmap_active_record.png %> alt="Active Records and SqlMap DataMapper" id="fig:diagram.png" class="figure"/>
34
    </p>
35
 
36
    <p id="690482" class="block-content">
37
        Klasa Rekordu aktywnego posiada funkcjonalność do przeprowadzenia następujących zadań:
38
    </p>
39
    <ul id="u1" class="block-content">
40
        <li>Tworzenie, zwracanie, aktualizowani i usuwanie recordów (CRUD)</li>
41
        <li>metody wyszukujące obudowujące powszechnie używane zapytania SQL i zwracające obiekty Rekordu Aktywnego</li>
42
        <li>Wydobywają relacje (powiazanych obcych obiektów) takie jak "posiada wiele" (ang. has many), "posiada jedno" (ang. has one), "należy do" (ang. belongs to) oraz wiele do wielu "many to many" poprzez tablice asocjacyjne.</li>
43
        <li>Opóźnione ładowanie (ang. Lazy loading) relacji</li>
44
    </ul>
45
<h2>Implikacje modelu</h2>
46
<p>
47
Implementacja wzorca Aktywnego Rekordu w PRADO nie zapewnia referencyjnej tożsamości (ang. referential identity). Każdy istniejący obiekt używający
48
Rekordu Aktywnego jest koopią danych z bazy danych. Na przykład jeśli zapytasz o konkretnego klienta i zostanie zwrócony obiekt <tt>Klient</tt>,
49
to następnym razem kiedy zapytasz o tego klienta otrzymasz spowrotem inną instancję obiektu <tt>Klient</tt>. To implikuje, że ścisłe porównianie (np. używając <tt>===</tt>)
50
zwróci fałsz, natomiast luźne porównianie (np. używając <tt>==</tt>) zwróci prawdę jeśli wartości obiektu są równe poprzez luźne porónanie.
51
<p>
52
<p>
53
Jest to implikacja modelu wynikająca z następującego pytania:
54
<i>"Czy myślisz o kliencie jako o obiekcie, którego któy jest tylko jeden, czy też myślisz o obiekcie na którym działasz jako o <b>kopii</b> bazy danych.</i>
55
Inne mapowania O/R implikują, że istnieje tylko jeden obiekt Klienta z KlientID 100
56
Other O/R mappings will imply that there is only one Customer object with custID 100 i to dosłownie jest ten klient.
57
Jeśli pobierzesz klienta i zmienisz pole w nim, wtedy masz zmienionego tego klienta.
58
<i>"To kontroastuje z: zmieniłeś tą kopię klienta ale nie tamtą kopię.
59
Jeśli dwóch ludzi zaktualizuje kleinta z dwóch kopii obiektu, kto zaktualizuje pierwszy lub być może ostanie wygrywa."</i> [A. Hejlsberg 2003]
60
</p>
61
 
62
<h2 id="142010">Wspierane bazy danych</h2>
63
<p id="p1" class="block-content">
64
Implementacja Aktywnego Rekordu wykorzystuje kalsy <a href="?page=Database.DAO">Prado DAO</a> by uzyskać dostęp do danych. Aktualna implementacja Aktywnego Rekordu wspiera następujace bazy danych
65
</p>
66
<ul>
67
    <li><a href="http://www.mysql.com">MySQL 4.1 i wyższe</a></li>
68
    <li><a href="http://www.postgres.com">Postgres SQL 7.3 i wyższe</a></li>
69
    <li><a href="http://www.sqlite.org">SQLite 2 i 3</a></li>
70
    <li><a href="#">MS SQL 2000 i wyższe</a></li>
71
    <li><a href="http://www.oracle.com">Oracle Database (alfa)</a></li>
72
</ul>
73
<p id="710009" class="block-content">Wsparcie dla pozostałych baz danych może zostać wprowadzone, keidy będzie dostatecne zapotrzebowanie</p>
74
 
75
<h1 id="138048">Definiowanie Aktywnego Rekordu</h1>
76
<p id="690483" class="block-content">Rozważmy następującą tablicę "<tt>users</tt>", która zawiera dwie kolumny nazwane "<tt>username</tt>" oraz "<tt>email</tt>",
77
    gdzie "<tt>username</tt>" jest kluczem głównym.
78
<com:TTextHighlighter Language="sql" CssClass="source block-content" id="code_690147">
79
CREATE TABLE users
80
(
81
    username VARCHAR( 20 ) NOT NULL ,
82
    email VARCHAR( 200 ) ,
83
    PRIMARY KEY ( username )
84
);
85
</com:TTextHighlighter>
86
</p>
87
<p id="690484" class="block-content">Następnie zdefiniujemy naszą klasę Rekordu Aktywnego odpowiadającą tablicy "<tt>users</tt>".
88
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690148">
89
class UserRecord extends TActiveRecord
90
{
91
    const TABLE='users'; //nazwa tablicy
92
 
93
    public $username; //kolumna nazwana "username" w tablicy "users"
94
    public $email;
95
 
96
    /**
97
     * @return TActiveRecord intancja finder rekordu aktywnego
98
     */
99
    public static function finder($className=__CLASS__)
100
    {
101
        return parent::finder($className);
102
    }
103
}
104
</com:TTextHighlighter>
105
</p>
106
<p id="690485" class="block-content">Każda kolumna tablicy "<tt>users</tt>" musi posiadać odpowiadającą jej właściwość o tej samej nazwie co kolumna w tablicy w klasie <tt>UserRecord</tt>.
107
    Oczywiście, możesz zdefiniować dodatkowe zmienne lub właściwości, które nie istnieją w strukturze tablicy.
108
    Stała <tt>TABLE</tt> jest opcjonalna w klasie , kiedy nazwa klasy jest taka sama jak nazwa tablicy w bazie danych, w przeciwnym przypadku <tt>TABLE</tt>
109
    musi określać nazwę tablicy, która odpowiada klasie Rekordu Aktywnego.
110
</p>
111
 
112
<div class="tip"><b class="note">Tip:</b>
113
Możesz określić kwalifikowane (ang. qualified) nazwy tablic np dla MySQL, <tt>TABLE = "`bazadanych1`.`tablica1`"</tt>.
114
</div>
115
 
116
<p class="block-content" id="ar_as_component">
117
    Odkąd <tt>TActiveRecord</tt> rozszerza <tt>TComponent</tt>, metody setter i getter mogą zostać zdefiniowane
118
    by umożliwić kontrolę nad tym jak zmienne są ustawiane i zwracane. Na przykłąd dodanie właściwości <tt>$level</tt>
119
    do klasy UserRecord:
120
</p>
121
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690149">
122
class UserRecord extends TActiveRecord {
123
    ... //istniejąca uprzednio część definicji
124
 
125
    private $_level;
126
    public function setLevel($value) {
127
        $this->_level=TPropertyValue::ensureInteger($value,0);
128
    }
129
    public function getLevel($value){
130
        return $this->_level;
131
    }
132
}
133
</com:TTextHighlighter>
134
<p id="710010" class="block-content">Więcej szczegółów dotyczących TComponent można znaleźć <a href="?page=Fundamentals.Components">dokumentacji komponentów</a>.
135
Później użyjemy metod getter/setters by umożliwić opóźnione ładowanie (ang. lazy loading) obiektów relacji.
136
</p>
137
 
138
<div class="info"><b class="note">Info:</b>
139
<tt>TActiveRecord</tt> może również działać z widokami poprzez przypisanie do stałej <tt>TABLE</tt>
140
 odpowiedniej nazwy widoku. Jednakże obiektu zwracane przez widoki są tylko do odczytu, wywołanie metod <tt>save()</tt> lub <tt>delete()</tt>
141
spowoduje wywołanie wyjątku.
142
</div>
143
 
144
<p id="690486" class="block-content">
145
    Metoda statyczna <tt>finder()</tt> zwraca instancję <tt>UserRecord</tt>, która może zostać użyta do załadowania rekordów z bazy.
146
    Ładowanie rekordów za pomocą tej metody będzie omówione później. Statyczna metoda <tt>TActiveRecord::finder()</tt>
147
    pobiera nazwę klasy Rekord Aktywnego jako parametr.
148
</p>
149
 
150
<h2 id="138049">Ustanawianie połączenia z bazą danych</h2>
151
<p id="690487" class="block-content">
152
    Domyślne połączenie z bazą dla Rekordu Aktywnego może zostać ustawione następujaco.
153
    Zobacz <a href="?page=Database.DAO">Ustanawianie połączenia z bazą</a>
154
    by uzyskać ogólnie dalsze szczegóły odnośnie tworzenia połączenia z bazą danych.
155
</p>
156
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690150">
157
//utwóz połączenie i przekaż je do menadżera Rekordu Aktywnego
158
$dsn = 'pgsql:host=localhost;dbname=test'; //Postgres SQL
159
$conn = new TDbConnection($dsn, 'dbuser','dbpass');
160
TActiveRecordManager::getInstance()->setDbConnection($conn);
161
</com:TTextHighlighter>
162
 
163
<p id="710011" class="block-content">Alternatywnie, możesz stworzyć klasę bazową i nadpisać metodę <tt>getDbConnection()</tt>
164
do zwracania połączenia z bazą. To jest prosty spodób, by umożliwić wielkokrotne połączenia do wielu baz danych.
165
 Następujący kod demonstruje definiowanie połączenia z bazą danych w klasie bazowej (nie ma potrzeby by ustawiać połączenie DB gdziekolwiek indziej).
166
</p>
167
<com:TTextHighlighter Language="php" CssClass="source block-content">
168
class MyDb1Record extends TActiveRecord
169
{
170
    public function getDbConnection()
171
    {
172
        static $conn;
173
        if($conn===null)
174
            $conn = new TDbConnection('xxx','yyy','zzz');
175
        return $conn;
176
    }
177
}
178
class MyDb2Record extends TActiveRecord
179
{
180
    public function getDbConnection()
181
    {
182
        static $conn;
183
        if($conn===null)
184
            $conn = new TDbConnection('aaa','bbb','ccc');
185
        return $conn;
186
    }
187
}
188
</com:TTextHighlighter>
189
 
190
 
191
<h3 class="prado-specific">Używanie <tt>application.xml</tt> w frameworku Prado</h3>
192
<div class="prado-specific">
193
<p id="690488" class="block-content">
194
    Domyślne połączenie z bazą może zostać również skonfigurowane używając tagu <tt>&lt;module&gt;</tt>
195
    w pliku <a href="?page=Configurations.AppConfig">application.xml</a>
196
    lub <a href="?page=Configurations.PageConfig">config.xml</a> następująco:
197
<com:TTextHighlighter Language="xml" CssClass="source block-content" id="code_690151">
198
<modules>
199
  <module class="System.Data.ActiveRecord.TActiveRecordConfig" EnableCache="true">
200
    <database ConnectionString="pgsql:host=localhost;dbname=test"
201
        Username="dbuser" Password="dbpass" />
202
  </module>
203
</modules>
204
</com:TTextHighlighter>
205
<div class="tip"><b class="note">Wskazówka:</b>
206
    Atrybut <tt>EnableCache</tt> gdy ustawiony na "true" będzie keszował metadane tablicy, to oznacza, że nazwy kolumn, indeksy i ograniczenia (ang. constraints)
207
    są zapisywane w keszu i używane ponownie. Musisz wyczyścić lub wyłączyć kesz jeśli chcesz zobaczyć wprowadzone zmiany do definicji twoich tablic.
208
    <a href="?page=Advanced.Performance#6402">Moduł keszowania</a> musi być również zdefiniowany dla keszu by zadziałał.
209
</div>
210
</p>
211
 
212
<p id="690489" class="block-content">Do właściwość <tt>ConnectionID</tt> może zostać przypisana wartość ID z konfiguracji z innego modułu
213
    <tt>TDataSourceConfig</tt>. To pozwala uyżywać to połączenie z bazą danych w innych modułach, takich jak <a href="?page=Database.SqlMap">SqlMap</a> (mapa SQL).
214
<com:TTextHighlighter Language="xml" CssClass="source block-content" id="code_690152">
215
<modules>
216
  <module class="System.Data.TDataSourceConfig" id="db1">
217
    <database ConnectionString="pgsql:host=localhost;dbname=test"
218
        Username="dbuser" Password="dbpass" />
219
  </module>
220
 
221
  <module class="System.Data.ActiveRecord.TActiveRecordConfig"
222
        ConnectionID="db1" EnableCache="true"  />
223
 
224
  <module class="System.Data.SqlMap.TSqlMapConfig"
225
        ConnectionID="db1"  ... />
226
</modules>
227
</com:TTextHighlighter>
228
</p>
229
</div>
230
 
231
<h2 id="138050">Ładowanie danych z tablicy</h2>
232
<p id="690490" class="block-content">
233
    Klasa <tt>TActiveRecord</tt> dostarcza wielu wygodnych metod do wyszukiwania rekordów z bazy danych.
234
    Najprostszym jest znajdowanie jednego rekordu poprzez dopasowanie klucza głównego lub klucza złożonego (ang. composite key)
235
    (klucz główny skłądający się z wielu kolumn).
236
    Zobacz  <com:DocLink ClassPath="System.Data.ActiveRecord.TActiveRecord" /> by dowiedzieć się więcej.
237
</p>
238
 
239
<div class="info"><b class="note">Info:</b>
240
Wszystkie metody wyszukujące, które mogą zwrócić tylko 1 rekord zwrócą <tt>null</tt> jeśli nie znajdą pasujących danych.
241
Wszystkie metody wyszukujące, które zwracają tablicę rekordów zwrócą pustą tablicęm jeśli nie znajdą pasujących danych.
242
</div>
243
 
244
	<h3 id="138055"><tt>findByPk()</tt></h3>
245
    <p id="690491" class="block-content">Znajduje jeden rekord używając klucza głównego lub klucza złożonego.
246
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690153">
247
$finder = UserRecord::finder();
248
$user = $finder->findByPk($primaryKey);
249
 
250
//kiedy tablica używa klucza złożonego
251
$record = $finder->findByPk($key1, $key2, ...);
252
$record = $finder->findByPk(array($key1, $key2,...));
253
</com:TTextHighlighter>
254
</p>
255
 
256
    <h3 id="138056"><tt>findAllByPks()</tt></h3>
257
    <p id="690492" class="block-content">Znajduje wiele rekordów używając listy kluczy głównych lub kluczy złożonych.
258
Co następuje jest odpowiednie dla kluczów głównych (klucz główny składa się tylko z jednego pola/kolumny)
259
</p>
260
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690154">
261
$finder = UserRecord::finder();
262
$users = $finder->findAllByPks($key1, $key2, ...);
263
$users = $finder->findAllByPks(array($key1, $key2, ...));
264
</com:TTextHighlighter>
265
Co następuje jest odpowiednie dla kluczów złożonych:
266
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690155">
267
//kiedy tablica używa klucza złożonego
268
$record = $finder->findAllByPks(array($key1, $key2), array($key3, $key4), ...);
269
 
270
$keys = array(  array($key1, $key2), array($key3, $key4), ... );
271
$record = $finder->findAllByPks($keys);
272
</com:TTextHighlighter>
273
 
274
 
275
<h3 id="138057"><tt>find()</tt></h3>
276
<p id="690493" class="block-content">Znajduje <b>pojedyńczy rekord</b>, który spełnia kryteria. Kryteria mogą być częściowym łąńcuchem SQL lub obiektem <tt>TActiveRecordCriteria</tt></p>
277
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690156">
278
$finder = UserRecord::finder();
279
 
280
//:name oraz :pass są pojemnikami dla konkretnych wartości $name oraz $pass
281
$finder->find('username = :name AND password = :pass',
282
                          array(':name'=>$name, ':pass'=>$pass));
283
 
284
//użycie znaków zastępczych
285
$finder->find('username = ? AND password = ?', array($name, $pass));
286
//jak wyżej
287
$finder->find('username = ? AND password = ?', $name, $pass);
288
 
289
//$criteria są typu TActiveRecordCriteria
290
$finder->find($criteria); //drugi parametr dla find() jest zignorowany.
291
</com:TTextHighlighter>
292
 
293
<p id="690494" class="block-content">Klasa <tt>TActiveRecordCriteria</tt> ma następujące właściwości:
294
</p>
295
    <ul id="u2" class="block-content">
296
        <li><tt>Parameters</tt> -- pary wartość nazwa parametru.</li>
297
        <li><tt>OrdersBy</tt> -- nazwa kolumny i sortowanie par</li>
298
        <li><tt>Condition</tt> -- część WHERE zapytania SQL</li>
299
        <li><tt>Limit</tt> -- maksymalna ilość rekordów, któe zostaną zwrócone.</li>
300
        <li><tt>Offset</tt> -- offset rekordów w tablicy.</li>
301
    </ul>
302
 
303
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690157">
304
$criteria = new TActiveRecordCriteria;
305
$criteria->Condition = 'username = :name AND password = :pass';
306
$criteria->Parameters[':name'] = 'admin';
307
$criteria->Parameters[':pass'] = 'prado';
308
$criteria->OrdersBy['level'] = 'desc';
309
$criteria->OrdersBy['name'] = 'asc';
310
$criteria->Limit = 10;
311
$criteria->Offset = 20;
312
</com:TTextHighlighter>
313
 
314
<div class="note"><b class="note">Przypis:</b>
315
For MSSQL and when <tt>Limit</tt> and <tt>Offset</tt> are positive integer values. The
316
actual query to be executed is modified by the
317
<com:DocLink ClassPath="System.Data.ActiveRecord.Common.Mssql.TMssqlCommandBuilder"
318
Text="TMssqlCommandBuilder"
319
/>
320
class according to
321
<a href="http://troels.arvin.dk/db/rdbms/#select-limit-offset">http://troels.arvin.dk/db/rdbms/</a>
322
to emulate the <tt>Limit</tt> and <tt>Offset</tt> conditions.
323
</div>
324
 
325
<h3 id="138058"><tt>findAll()</tt></h3>
326
<p id="690495" class="block-content">Podobnie jak <tt>find()</tt> ale zwraca tablicę obiektów.</p>
327
 
328
<h3 id="138059"><tt>findBy*()</tt> oraz <tt>findAllBy*()</tt></h3>
329
<p id="690496" class="block-content">Dynamiczne metody wyszukujące używające część nazwy metody jako kryteria wyszukiwania.
330
Metody zaczynające się od słów <tt>findBy</tt> zwracają tylko 1 rekord natomiast metody zaczynające się  <tt>findAllBy</tt> zwracają tablicę obiektów.
331
Warunej jest wzięty jako część nazwy metody po przedrostku <tt>findBy</tt> lub <tt>findAllBy</tt>.
332
 
333
Następujące bloki kodów są sobie równoważne:
334
</p>
335
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690158">
336
$finder->findByName($name)
337
$finder->find('Name = ?', $name);
338
</com:TTextHighlighter>
339
 
340
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690159">
341
$finder->findByUsernameAndPassword($name,$pass);
342
$finder->findBy_Username_And_Password($name,$pass);
343
$finder->find('Username = ? AND Password = ?', $name, $pass);
344
</com:TTextHighlighter>
345
 
346
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690160">
347
$finder->findAllByAge($age);
348
$finder->findAll('Age = ?', $age);
349
</com:TTextHighlighter>
350
 
351
<div class="tip"><b class="note">Tip:</b>
352
Możesz również użyć połączenia <tt>AND</tt> oraz <tt>OR</tt> jako warunek w dynamicznych metodach.
353
</div>
354
 
355
<h3 id="138060"><tt>findBySql()</tt> oraz <tt>findAllBySql()</tt></h3>
356
<p id="690497" class="block-content">Znajdują rekordy używając pełnego zapytania SQL z tym, że <tt>findBySql()</tt>
357
zwraca Rekord Aktywny a <tt>findAllBySql()</tt>zwraca tablicę obiektów rekordów.
358
Dla każdej zwróconej kolumny, odpowiadająca klasa Rekordu Aktywnego musi posiadać zdefiniowaną zmienną lub właściwość odpowiadającą nazwie kolumny.
359
<com:TTextHighlighter Language="php" CssClass="source block-content">
360
class UserRecord2 extends UserRecord
361
{
362
    public $another_value;
363
}
364
$sql = "SELECT users.*, 'hello' as another_value FROM users";
365
$users = TActiveRecord::finder('UserRecord2')->findAllBySql($sql);
366
</com:TTextHighlighter>
367
</p>
368
<h3 id="138061"><tt>count()</tt></h3>
369
<p id="690498" class="block-content">Zlicza ilość pasujących rekordów, akceptuje te same parametry co metoda <tt>findAll()</tt></p>
370
 
371
<h2 id="138051">Wstawianie i aktualizowanie rekordów</h2>
372
<p id="690499" class="block-content">
373
Dodanie nowego rekordu za pomocą TActiveRecord jest bardzo łatwe, po prostu stwórz nowy obiekt Rekordu Aktywnego i wywołaj metodę <tt>save()</tt>. Na przykład
374
</p>
375
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690161">
376
$user1 = new UserRecord();
377
$user1->username = "admin";
378
$user1->email = "admin@example.com";
379
$user1->save(); //wstaw nowy rekord
380
 
381
$data = array('username'=>'admin', 'email'=>'admin@example.com');
382
$user2 = new UserRecord($data); //stwórz przekazując istniejące dane
383
$user2->save(); //wstaw nowy rekord
384
</com:TTextHighlighter>
385
<div class="tip"><b class="note">Wskazówka:</b>
386
Obiekty są aktualizowe automatycznie o wartość klucza głównego dla tych tablic, które zawierają definicję
387
określającą automatyczne tworzenie klucza głównego dla nowo tworzonych rekordów (przyp. tłum. autoincrement).
388
Na przykład jeśli wstawiasz nowy rekord do tablicy MySQL która posiada kolumnę zdefiniowaną jako to obiekt Rekordu Aktywnego
389
zostanie zaktualizowant o nową zwiększoną wartość.</div>
390
 
391
<p id="690500" class="block-content">
392
Aby zaktualizować rekord w bazie danych po prostu zmień jedną lub więcej właściwości obiektu Rekordu Aktywnego które zostały odczytane z bazy a następnie wywołaj metodę <tt>save()</tt>.
393
 
394
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690162">
395
$user = UserRecord::finder()->findByName('admin');
396
$user->email="test@example.com"; //zmiana właściwości
397
$user->save(); //zaktualizuj ją
398
</com:TTextHighlighter>
399
</p>
400
 
401
<p id="710012" class="block-content">
402
Obiekt Rekordu Aktywnego posiada prosty cykl życia zilustrowany następujący diagram.
403
</p>
404
<img src=<%~ object_states.png %> alt="Active Records Life Cycle" id="fig:cycle.png" class="figure"/>
405
<p id="690501" class="block-content">
406
Widzimy, że nowe obiekty Rekordu Aktywnego są tworzone zarówno przez jedną z metod <tt>find*()</tt>
407
lub poprzez stworzenie nowej instancji poprzez użycie polecenia PHP <tt>new</tt>. Obiekty stworzone przez metodę <tt>find*()</tt>
408
zaczynają ze stanem <tt>czysty (ang. clean)</tt>. Nowa instancja TActiveRecord stworzona inaczej niż za pomocą metod <tt>find*()</tt> zaczyna ze stanem <tt>nowy (ang. new)</tt>.
409
Kiedykolwiek wywołasz metodę <tt>save()</tt> na obiekcie TActiveRecord, obiekt przyjmuje stan <tt>czysty</tt>.
410
Obiekty będące <tt>czystymi</tt> stają się <tt>brudne (ang. dirty)</tt> kiedy jeden lub więcej ze stwoich wewnętrznych stanów ulegnie zmianie.
411
Wywoałanie metody <tt>delete()</tt> obiektu kończy cykl życia, żadne inne akcje nie mogą być wywołane na obiekcie.
412
</p>
413
 
414
<h2 id="138052">Usuwanie istniejących obiektów</h2>
415
<p id="690502" class="block-content">
416
  Aby usunąc istniejący rekord, który jest załadowany, po prostu wywołaj metodę <tt>delete</tt>.
417
  Możesz rónież usunąć rekord w bazie danych poprzez klucz główny bez ładowania żadnego rekordu używając metody
418
  <tt>deleteByPk()</tt> (również metoda <tt>deleteAllByPks()</tt>).
419
  Na przykład, aby usunąć jeden lub więcej rekordów z tabeli używając jednego lub wielu kluczów głównych:
420
</p>
421
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690163">
422
$finder->deleteByPk($primaryKey); //usuwanie 1 rekordu
423
$finder->deleteAllByPks($key1,$key2,...); //usuwanie wielu rekordów
424
$finder->deleteAllByPks(array($key1,$key2,...)); //usuwanie wielu rekordów
425
</com:TTextHighlighter>
426
 
427
<p id="690503" class="block-content">
428
Dla klucza złożonego (ustalanego automatycznie na podstawie definicji tablicy):
429
</p>
430
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690164">
431
$finder->deleteByPk(array($key1,$key2)); //usuwanie 1 rekordu
432
 
433
//usuwanie wielu rekordów
434
$finder->deleteAllByPks(array($key1,$key2), array($key3,$key4),...);
435
 
436
//usuwanie wielu rekordów
437
$finder->deleteAllByPks(array( array($key1,$key2), array($key3,$key4), .. ));
438
</com:TTextHighlighter>
439
 
440
<h3 id="138052a"><tt>deleteAll()</tt> oraz <tt>deleteBy*()</tt></h3>
441
<p id="690502a" class="block-content">
442
Aby usunąć używając kryteria użyj <tt>deleteAll($criteria)</tt> oraz <tt>deleteBy*()</tt>
443
z podobną składnią jak <tt>findAll($criteria)</tt> oraz <tt>findAllBy*()</tt> opisaną wcześniej.
444
</p>
445
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690163a">
446
//usuwanie wszystkich rekordów z pasującym Name
447
$finder->deleteAll('Name = ?', $name);
448
$finder->deleteByName($name);
449
 
450
//usuwanie na podstawie Name oraz Password
451
$finder->deleteBy_Username_And_Password($name,$pass);
452
</com:TTextHighlighter>
453
 
454
<h2 id="138053">Tranzakcje</h2>
455
<p id="690504" class="block-content">Wszystkie obiekkty Rekordu Aktywnego zawierają właściwość <tt>DbConnection</tt>,
456
 która może być używana by uzyskać obiekt tranzakcyjny.
457
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690165">
458
$finder = UserRecord::finder();
459
$finder->DbConnection->Active=true; //otwórz jeśli to konieczne
460
$transaction = $finder->DbConnection->beginTransaction();
461
try
462
{
463
    $user = $finder->findByPk('admin');
464
    $user->email = 'test@example.com'; //zmień obiekt użytkownika $user
465
    $user->save();
466
    $transaction->commit();
467
}
468
catch(Exception $e) // wyjątek jest wołany jeśli zapytanie nie powiedzie się
469
{
470
    $transaction->rollBack();
471
}
472
</com:TTextHighlighter>
473
 
474
<h2 id="142011">Zdarzenia</h2>
475
<p id="710013" class="block-content">
476
Rekord Aktywny oferuje dwa zdarzenia: <tt>OnCreateCommand</tt> oraz <tt>OnExecuteCommand</tt>.
477
</p>
478
 
479
<p id="710014" class="block-content">Zdarzenie <tt>OnCreateCommand</tt> jest wołane gdy polecenie jest przygotowywane i przypisywanie (ang. binding) parametrów jest zakończone.
480
 Parametrem obiektu jest <tt>TDataGatewayEventParameter</tt>, którego właściwość <tt>Command</tt> może być sprawdzona by otrzymać zapytanie, które będzie wykonane wykonywane.
481
</p>
482
 
483
<p id="710015" class="block-content">
484
Zdarzenie <tt>OnExecuteCommand</tt> jest wywoływane kiedy polecenie jest wykonane i rezultat z bazy danych został zwrócony.
485
 Parametrem obiektu jest <tt>TDataGatewayResultEventParameter</tt>, którego właściwość <tt>Result</tt> zawiera dane zwrócone z bazy danych.
486
 Dane zwrócone mogą zostać zmienione poprzez ustawienie właściwości <tt>Result</tt>.
487
</p>
488
 
489
<h3 id="142016">Przykład z logowaniem</h3>
490
<p id="710016" class="block-content">Używając <tt>OnExecuteCommand</tt> możemy przypiąć uchwyt zdarzenia by logować całe
491
zapytanie SQL wwywoływane dla danej instancji lub klasy TActiveRecord. Na przykład definiujemy klasę bazową i nadpisujemy
492
metodę <tt>getDbConnection()</tt> lub konstruktor.
493
</p>
494
 
495
<com:TTextHighlighter Language="php" CssClass="source block-content">
496
class MyDb1Record extends TActiveRecord
497
{
498
    public function getDbConnection()
499
    {
500
        static $conn;
501
        if($conn===null)
502
        {
503
            $conn = new TDbConnection('xxx','yyy','zzz');
504
            $this->OnExecuteCommand[] = array($this,'logger');
505
        }
506
        return $conn;
507
    }
508
    public function logger($sender,$param)
509
    {
510
        var_dump($param->Command->Text);
511
    }
512
}
513
//alternatively as per instance of per finder object
514
function logger($sender,$param)
515
{
516
    var_dump($param->Command->Text);
517
}
518
TActiveRecord::finder('MyRecord')->OnExecuteCommand[] = 'logger';
519
$obj->OnExecuteCommand[] = array($logger, 'log'); //dowolny poprawny callback PHP
520
</com:TTextHighlighter>
521
 
522
<h1 id="ar_relations">Relacje dla Rekordu Aktywnego</h1>
523
<com:SinceVersion Version="3.1rc1" />
524
<p id="690504a" class="block-content">
525
Implementacja Rekordu Aktywnego w Prado wspiera mapowanie kluczów obcych dla baz, które wspierają ograniczenia (ang. constraints) kluczów obcych.
526
 Aby relacje dla Rekordu Aktywnego działały używana baza danych musi wspierać ograniczenia klucza głównego (np. MySQL używająca InnoDB)
527
</p>
528
 
529
<p id="710017" class="block-content">
530
W następnych sekcjach będziemy rozważać nastepujące relacje pomiędzy tabelami <tt>Teams</tt>, <tt>Players</tt>, <tt>Skills</tt> oraz <tt>Profiles</tt>.
531
</p>
532
<img src=<%~ ar_relations.png %> class="figure" />
533
 
534
 
535
<p id="710018" class="block-content">Celem jest uzyskanie modelu obiektowego, który będzie reprezetnował w pewnym stopniu relacje pomiędzy polami z powyższego rysunku.
536
</p>
537
 
538
<img src=<%~ ar_objects.png %> class="figure" />
539
 
540
<p class="block-content">
541
Istnieje rozbieżność pomiędzy relacjami w obiektach i relacjami w tablicach.
542
 Po pierwsze jest różnica w reprezentacji. Obiekty trzymają powiązanie poprzez przechowywanie referencji,
543
które są trzymane poprzez zarządzające pamięcią środowiko uruchomieniowe. Bazy relacyjne trzymają powiązanie poprzez utworzenie klucza do innej tablicy.
544
 Po drugie, obiekty mogą łatwo uzywać kolekcji by trzymać wielokrotnie referencje z jednego pola,
545
to handle multiple references from a single field, gdyż normalizacja zmusza wszystkie powiązania relacji encji by były pojedyńczymi wartościami.
546
To prowadzi do odwrócenia struktury danych pomiędzy obiektami i tablicami.
547
Podejście zastosowane w modelu Rekordu Aktywnego Prado uzywa ograniczeń kluczów obcych tablicy do wyprowadzenia relacji obiektów.
548
To implikuje fakt wspierania ograniczeń kluczów obcych dla bazy danych.
549
</p>
550
<div class="tip"><b class="note">Tip:</b>
551
Dla baz danych SQLite możesz stworzyć tablice, które definiują ograniczenia kluczó obcych tak jak na przykładzie poniżej.
552
Jednakże te ograniczenia <b>NIE SĄ</b> narzucane przez samą bazę SQLite.
553
<com:TTextHighlighter Language="sql" CssClass="source block-content">
554
CREATE TABLE foo
555
(
556
    id INTEGER NOT NULL PRIMARY KEY,
557
    id2 CHAR(2)
558
);
559
CREATE TABLE bar
560
(
561
    id INTEGER NOT NULL PRIMARY KEY,
562
    foo_id INTEGER
563
        CONSTRAINT fk_foo_id REFERENCES foo(id) ON DELETE CASCADE
564
);
565
</com:TTextHighlighter>
566
</div>
567
 
568
<h2 id="142012">Mapowanie kluczów obcych</h2>
569
<p class="block-content">Relacja pól pomiędzy tablicami <tt>Teams</tt> and <tt>Players</tt> jest znana jako relacja jeden-do-wielu (ang. 1-M). Oznacza to, że jeden Team moze zawierać zero lub więcej Players. Z punktu widzenia relacji obiektów
570
powiemy, że obiekt <tt>TeamRecord</tt> <b>posiada wiele</b> (ang. has many) obiektów <tt>PlayerRecord</tt>.
571
(Zauważ odwrócenie kierunku relacji pomiędzy tablicami a obiektami)
572
</p>
573
 
574
<h3 id="142017">Relacja posiada wiele (ang. has Many Relationship)</h3>
575
<p id="710020" class="block-content">
576
Zamodelujemy obiekt <tt>Team</tt> jako następującą klasę Rekordu Aktywnego.
577
</p>
578
<com:TTextHighlighter Language="php" CssClass="source block-content">
579
class TeamRecord extends TActiveRecord
580
{
581
    const TABLE='Teams';
582
    public $name;
583
    public $location;
584
 
585
    public $players=array();  // this declaration is no longer needed since v3.1.2
586
 
587
    //define the $player member having has many relationship with PlayerRecord
588
    public static $RELATIONS=array
589
    (
590
        'players' => array(self::HAS_MANY, 'PlayerRecord', 'team_name'),
591
    );
592
 
593
    public static function finder($className=__CLASS__)
594
    {
595
        return parent::finder($className);
596
    }
597
}
598
</com:TTextHighlighter>
599
<p id="710021" class="block-content">
600
The static <tt>$RELATIONS</tt> property of <tt>TeamRecord</tt> defines that the
601
property <tt>$players</tt> <b>has many</b> <tt>PlayerRecord</tt>s. Multiple relationships
602
is permitted by defining each relationship with an entry in the <tt>$RELATIONS</tt>
603
array where array key for the entry corresponds to the property name.
604
In <tt>array(self::HAS_MANY, 'PlayerRecord')</tt>, the first element defines the
605
relationship type, the valid types are <tt>self::HAS_MANY</tt>, <tt>self::HAS_ONE</tt>,
606
<tt>self::BELONGS_TO</tt> and <tt>self::MANY_TO_MANY</tt>.
607
The second element is a string <tt>'PlayerRecord'</tt> that corresponds to the
608
class name of the <tt>PlayerRecord</tt> class.
609
And the third element 'team_name' refers to the foreign key column in the Players table that
610
references to the Teams table.
611
</p>
612
 
613
<div class="note"><b class="note">Note:</b>
614
As described in the code comment above, since version <b>3.1.2</b>, related properties no longer
615
need to be explicitly declared. By default, they will be implicitly declared according to
616
keys of the <tt>$RELATIONS</tt> array. A major benefit of declared related properties implicitly
617
is that related objects can be automatically loaded in a lazy way. For example, assume we have
618
a <tt>TeamRecord</tt> instance <tt>$team</tt>. We can access the players via <tt>$team->players</tt>,
619
even if we have never issued fetch command for players. If <tt>$players</tt> is explicitly declared,
620
we will have to use the <tt>with</tt> approach described in the following to fetch the player records.
621
</div>
622
 
623
<p id="710022" class="block-content">
624
The foreign key constraint of the <tt>Players</tt> table is used to determine the corresponding
625
<tt>Teams</tt> table's corresponding key names. This is done automatically handled
626
in Active Record by inspecting the <tt>Players</tt> and <tt>Teams</tt> table definitions.
627
</p>
628
 
629
<div class="info"><b class="note">Info:</b>
630
Since version <b>3.1.2</b>, Active Record supports multiple foreign key
631
references of the same table. Ambiguity between multiple foreign key references to the same table is
632
resolved by providing the foreign key column name as the 3rd parameter in the relationship array.
633
For example, both of the following foreign keys <tt>owner_id</tt> and <tt>reporter_id</tt>
634
references to the same table defined in <tt>UserRecord</tt>.
635
<com:TTextHighlighter Language="php" CssClass="source block-content">
636
class TicketRecord extends TActiveRecord
637
{
638
     public $owner_id;
639
	 public $reporter_id;
640
 
641
     public $owner;     // this declaration is no longer needed since v3.1.2
642
	 public $reporter;  // this declaration is no longer needed since v3.1.2
643
 
644
	 public static $RELATION=array
645
	 (
646
	     'owner' => array(self::BELONGS_TO, 'UserRecord', 'owner_id'),
647
		 'reporter' => array(self::BELONGS_TO, 'UserRecord', 'reporter_id'),
648
	 );
649
}
650
</com:TTextHighlighter>
651
This is applicable to relationships including <tt>BELONGS_TO</tt>, <tt>HAS_ONE</tt> and
652
<tt>HAS_MANY</tt>. See section <a href="#142021">Self Referenced Association Tables</a> for solving ambiguity of <tt>MANY_TO_MANY</tt>
653
relationships.
654
</div>
655
 
656
<p id="710023" class="block-content">The "has many" relationship is not fetched automatically when you use any of the Active Record finder methods.
657
You will need to explicitly fetch the related objects as follows. In the code below, both lines
658
are equivalent and the method names are case insensitive.
659
</p>
660
<com:TTextHighlighter Language="php" CssClass="source block-content">
661
$team = TeamRecord::finder()->withPlayers()->findAll();
662
$team = TeamRecord::finder()->with_players()->findAll(); //equivalent
663
</com:TTextHighlighter>
664
<p id="710024" class="block-content">
665
The method <tt>with_xxx()</tt> (where <tt>xxx</tt> is the relationship property
666
name, in this case, <tt>players</tt>) fetches the corresponding PlayerRecords using
667
a second query (not by using a join). The <tt>with_xxx()</tt> accepts the same
668
arguments as other finder methods of TActiveRecord, e.g. <tt>with_players('age = ?', 35)</tt>.
669
</p>
670
 
671
<div class="note"><b class="note">Note:</b>
672
It is essential to understand that the related objects are fetched using additional
673
queries. The first query fetches the source object, e.g. the <tt>TeamRecord</tt> in the above example code.
674
A second query is used to fetch the corresponding related <tt>PlayerRecord</tt> objects.
675
The usage of the two query is similar to a single query using Left-Outer join with the
676
exception that null results on the right table
677
are not returned. The consequence of using two or more queries is that the aggregates
678
and other join conditions are not feasible using Active Records. For queries outside the
679
scope of Active Record the <a href="?page=Database.SqlMap">SqlMap Data Mapper</a> may be considered.
680
</div>
681
 
682
<div class="info"><b class="info">Info:</b>
683
The above <tt>with</tt> approach also works with implicitly declared related properties (introduced
684
in version 3.1.2). So what is the difference between the <tt>with</tt> approach and the lazy loading
685
approach? Lazy loading means we issue an SQL query if a related object is initially accessed and not ready,
686
while the <tt>with</tt> approach queries for the related objects once for all, no matter the related objects
687
are accessed or not. The lazy loading approach is very convenient since we do not need to explictly
688
load the related objects, while the <tt>with</tt> approach is more efficient if multiple records are
689
returned, each with some related objects.
690
</div>
691
 
692
<h3 id="142019">Has One Relationship</h3>
693
<p id="710030" class="block-content">The entity relationship between <tt>Players</tt> and <tt>Profiles</tt> is one to one. That is,
694
each <tt>PlayerRecord</tt> object <b>has one</b> <tt>ProfileRecord</tt> object (may be none or null).
695
A <b>has one</b> relationship is nearly identical to a <b>has many</b> relationship with the exception
696
that the related object is only one object (not a collection of objects).
697
</p>
698
 
699
<h3 id="142018">Belongs To Relationship</h3>
700
<p id="710025" class="block-content">The "has many" relationship in the above section defines a collection of foreign
701
objects. In particular, we have that a <tt>TeamRecord</tt> has many (zero or more)
702
<tt>PlayerRecord</tt> objects. We can also add a back pointer by adding a property
703
in the <tt>PlayerRecord</tt> class that links back to the <tt>TeamRecord</tt> object,
704
effectively making the association bidirectional.
705
We say that the <tt>$team</tt> property in <tt>PlayerRecord</tt> class <tt>belongs to</tt> a <tt>TeamRecord</tt> object.
706
The following code defines the complete <tt>PlayerRecord</tt> class with 3 relationships.
707
</p>
708
<com:TTextHighlighter Language="php" CssClass="source block-content">
709
class PlayerRecord extends TActiveRecord
710
{
711
    const TABLE='Players';
712
    public $player_id;
713
    public $age;
714
    public $team_name;
715
 
716
    public $team;              // this declaration is no longer needed since v3.1.2
717
    public $skills=array();    // this declaration is no longer needed since v3.1.2
718
    public $profile;           // this declaration is no longer needed since v3.1.2
719
 
720
    public static $RELATIONS=array
721
    (
722
        'team' => array(self::BELONGS_TO, 'TeamRecord', 'team_name'),
723
        'skills' => array(self::MANY_TO_MANY, 'SkillRecord', 'Player_Skills'),
724
        'profile' => array(self::HAS_ONE, 'ProfileRecord', 'player_id'),
725
    );
726
 
727
    public static function finder($className=__CLASS__)
728
    {
729
        return parent::finder($className);
730
    }
731
}
732
</com:TTextHighlighter>
733
<p id="710026" class="block-content">
734
The static <tt>$RELATIONS</tt> property of <tt>PlayerRecord</tt> defines that the
735
property <tt>$team</tt> <b>belongs to</b> a <tt>TeamRecord</tt>.
736
The <tt>$RELATIONS</tt> array also defines two other relationships that we
737
shall examine in later sections below.
738
In <tt>array(self::BELONGS_TO, 'TeamRecord', 'team_name')</tt>, the first element defines the
739
relationship type, in this case <strong><tt>self::BELONGS_TO</tt></strong>;
740
the second element is a string <tt>'TeamRecord'</tt> that corresponds to the
741
class name of the <tt>TeamRecord</tt> class; and the third element 'team_name' refers
742
to the foreign key of Players referencing Teams.
743
A player object with the corresponding team object may be fetched as follows.
744
</p>
745
<com:TTextHighlighter Language="php" CssClass="source block-content">
746
$players = PlayerRecord::finder()->with_team()->findAll();
747
</com:TTextHighlighter>
748
 
749
<p id="710027" class="block-content">
750
 The method <tt>with_xxx()</tt> (where <tt>xxx</tt> is the relationship property
751
 name, in this case, <tt>team</tt>) fetches the corresponding <tt>TeamRecords</tt> using
752
 a second query (not by using a join). The <tt>with_xxx()</tt> accepts the same
753
arguments as other finder methods of <tt>TActiveRecord</tt>, e.g.
754
<tt>with_team('location = ?', 'Madrid')</tt>.
755
</p>
756
 
757
<div class="tip"><b class="note">Tip:</b>
758
Additional relationships may be fetched by chaining the <tt>with_xxx()</tt> together as the following
759
example demonstrates.
760
<com:TTextHighlighter Language="php" CssClass="source block-content">
761
$players = PlayerRecord::finder()->with_team()->with_skills()->findAll();
762
</com:TTextHighlighter>
763
Each <tt>with_xxx()</tt> method will execute an additional SQL query. Every
764
<tt>with_xxx()</tt> accepts arguments similar to those in the <tt>findAll()</tt> method and is only
765
applied to that particular relationship query.
766
</div>
767
 
768
<p id="710028" class="block-content">The "belongs to" relationship of <tt>ProfileRecord</tt> class is defined similarly.</p>
769
<com:TTextHighlighter Language="php" CssClass="source block-content">
770
class ProfileRecord extends TActiveRecord
771
{
772
    const TABLE='Profiles';
773
    public $player_id;
774
    public $salary;
775
 
776
    public $player;  // this declaration is no longer needed since v3.1.2
777
 
778
    public static $RELATIONS=array
779
    (
780
        'player' => array(self::BELONGS_TO, 'PlayerRecord'),
781
    );
782
 
783
    public static function finder($className=__CLASS__)
784
    {
785
        return parent::finder($className);
786
    }
787
}
788
</com:TTextHighlighter>
789
 
790
<p id="710029" class="block-content">In essence, there exists a "<b>belongs to</b>" relationship for objects corresponding to
791
entities that has column which are foreign keys. In particular, we see that
792
the <tt>Profiles</tt> table has a foreign key constraint on the column <tt>player_id</tt>
793
that relates to the <tt>Players</tt> table's <tt>player_id</tt> column. Thus, the <tt>ProfileRecord</tt>
794
object has a property (<tt>$player</tt>) that <b>belongs to</b> a <tt>PlayerRecord</tt> object.
795
Similarly, the <tt>Players</tt> table has a foreign key constraint on the column <tt>team_name</tt> that relates to the
796
<tt>Teams</tt> table's <tt>name</tt> column.
797
Thus, the <tt>PlayerRecord</tt> object has a property (<tt>$team</tt>) that <b>belongs to</b> a
798
<tt>TeamRecord</tt> object.
799
</p>
800
 
801
<h3 id="142020">Parent Child Relationships</h3>
802
<p id="710031" class="block-content">A parent child relationship can be defined using a combination of <tt>has many</tt> and <tt>belongs to</tt>
803
relationship that refers to the same class. The following example shows a parent children relationship between
804
"categories" and a "parent category".
805
</p>
806
 
807
<com:TTextHighlighter Language="php" CssClass="source block-content">
808
class Category extends TActiveRecord
809
{
810
    public $cat_id;
811
    public $category_name;
812
    public $parent_cat_id;
813
 
814
    public $parent_category;            // this declaration is no longer needed since v3.1.2
815
    public $child_categories=array();   // this declaration is no longer needed since v3.1.2
816
 
817
    public static $RELATIONS=array
818
    (
819
        'parent_category' => array(self::BELONGS_TO, 'Category', 'parent_cat_id'),
820
        'child_categories' => array(self::HAS_MANY, 'Category', 'parent_cat_id'),
821
    );
822
}
823
</com:TTextHighlighter>
824
 
825
<h3>Query Criteria for Related Objects</h3>
826
<p>
827
In the above, we show that an Active Record object can reference to its related objects by
828
declaring a static class member $RELATIONS which specifies a list of relations. Each relation
829
is specified as an array consisting of three elements: relation type, related AR class name,
830
and the foreign key(s). For example, we use <tt>array(self::HAS_MANY, 'PlayerRecord', 'team_name')</tt>
831
to specify the players in a team. There are two more optional elements that can be specified
832
in this array: query condition (the fourth element) and parameters (the fifth element).
833
They are used to control how to query for the related objects. For example, if we want to obtain
834
the players ordered by their age, we can specify <tt>array(self::HAS_MANY, 'PlayerRecord', 'team_name', 'ORDER BY age')</tt>.
835
If we want to obtain players whose age is smaller than 30, we could use
836
<tt>array(self::HAS_MANY, 'PlayerRecord', 'team_name', 'age<:age', array(':age'=>30))</tt>. In general,
837
these two additional elements are similar as the parameters passed to the <tt>find()</tt> method in AR.
838
</p>
839
 
840
 
841
 
842
<h2 id="142013">Association Table Mapping</h2>
843
<p id="710032" class="block-content">
844
Objects can handle multivalued fields quite easily by using collections as field values.
845
Relational databases don't have this feature and are constrained to single-valued fields only.
846
When you're mapping a one-to-many association you can handle this using <b>has many</b> relationships,
847
essentially using a foreign key for the single-valued end of the association.
848
But a many-to-many association can't do this because there is no single-valued end to
849
hold the foreign key.
850
</p>
851
<p id="710033" class="block-content">
852
The answer is the classic resolution that's been used by relational data people
853
for decades: create an extra table (an association table) to record the relationship.
854
The basic idea is using an association table to store the association. This table
855
has only the foreign key IDs for the two tables that are linked together, it has one
856
row for each pair of associated objects.
857
</p>
858
<p id="710034" class="block-content">
859
The association table has no corresponding in-memory object and its primary key is the
860
compound of the two primary keys of the tables that are associated.
861
In simple terms, to load data from the association table you perform two queries (in general, it may also be achieved using one query consisting of joins).
862
Consider loading the <tt>SkillRecord</tt> collection for a list <tt>PlayerRecord</tt> objects.
863
In this case, you do queries in two stages.
864
The first stage queries the <tt>Players</tt> table to find all the rows of the players you want.
865
The second stage finds the <tt>SkillRecord</tt> object for the related player ID for each row
866
in the <tt>Player_Skills</tt> association table using an inner join.
867
</p>
868
 
869
<p id="710035" class="block-content">The Prado Active Record design implements the two stage approach. For the
870
<tt>Players</tt>-<tt>Skills</tt> M-N (many-to-many) entity relationship, we
871
define a <b>many-to-many</b> relationship in the <tt>PlayerRecord</tt> class and
872
in addition we may define a <b>many-to-many</b> relationship in the <tt>SkillRecord</tt> class as well.
873
The following sample code defines the complete <tt>SkillRecord</tt> class with a
874
many-to-many relationship with the <tt>PlayerRecord</tt> class. (See the <tt>PlayerRecord</tt>
875
class definition above to the corresponding many-to-many relationship with the <tt>SkillRecord</tt> class.)
876
</p>
877
 
878
<com:TTextHighlighter Language="php" CssClass="source block-content">
879
class SkillRecord extends TActiveRecord
880
{
881
    const TABLE='Skills';
882
    public $skill_id;
883
    public $name;
884
 
885
    public $players=array();    // this declaration is no longer needed since v3.1.2
886
 
887
    public static $RELATIONS=array
888
    (
889
        'players' => array(self::MANY_TO_MANY, 'PlayerRecord', 'Player_Skills'),
890
    );
891
 
892
    public static function finder($className=__CLASS__)
893
    {
894
        return parent::finder($className);
895
    }
896
}
897
</com:TTextHighlighter>
898
 
899
<p id="710036" class="block-content">
900
The static <tt>$RELATIONS</tt> property of SkillRecord defines that the
901
property <tt>$players</tt> has many <tt>PlayerRecord</tt>s via an association table '<tt>Player_Skills</tt>'.
902
In <tt>array(self::MANY_TO_MANY, 'PlayerRecord', 'Player_Skills')</tt>, the first element defines the
903
relationship type, in this case <strong><tt>self::MANY_TO_MANY</tt></strong>,
904
the second element is a string <tt>'PlayerRecord'</tt> that corresponds to the
905
class name of the <tt>PlayerRecord</tt> class, and the third element is the name
906
of the association table name.
907
</p>
908
 
909
<div class="note"><b class="note">Note:</b>
910
Prior to version <b>3.1.2</b> (versions up to 3.1.1), the many-to-many relationship was
911
defined using <tt>self::HAS_MANY</tt>. For version <b>3.1.2</b> onwards, this must be changed
912
to <tt>self::MANY_TO_MANY</tt>. This can be done by searching for the <tt>HAS_MANY</tt> in your
913
source code and carfully changing the appropriate definitions.
914
</div>
915
 
916
<p id="710037" class="block-content">
917
A list of player objects with the corresponding collection of skill objects may be fetched as follows.
918
</p>
919
<com:TTextHighlighter Language="php" CssClass="source block-content">
920
$players = PlayerRecord::finder()->withSkills()->findAll();
921
</com:TTextHighlighter>
922
<p id="710038" class="block-content">
923
The method <tt>with_xxx()</tt> (where <tt>xxx</tt> is the relationship property
924
name, in this case, <tt>Skill</tt>) fetches the corresponding <tt>SkillRecords</tt> using
925
a second query (not by using a join). The <tt>with_xxx()</tt> accepts the same
926
arguments as other finder methods of <tt>TActiveRecord</tt>.
927
</p>
928
 
929
<h3 id="142021">Self Referenced Association Tables</h3>
930
<p id="710039" class="block-content">
931
For self referenced association tables, that is, the association points to the same
932
table. For example, consider the <tt>items</tt> table with M-N related
933
item via the <tt>related_items</tt> association table. The syntax in the following
934
example is valid for a PostgreSQL database. For other database, consult their respective documentation for
935
defining the foreign key constraints.
936
<com:TTextHighlighter Language="sql" CssClass="source block-content">
937
CREATE TABLE items
938
(
939
  "item_id" SERIAL,
940
  "name" VARCHAR(128) NOT NULL,
941
  PRIMARY KEY("item_id")
942
);
943
CREATE TABLE "related_items"
944
(
945
  "item_id" INTEGER NOT NULL,
946
  "related_item_id" INTEGER NOT NULL,
947
  CONSTRAINT "related_items_pkey" PRIMARY KEY("item_id", "related_item_id"),
948
  CONSTRAINT "related_items_item_id_fkey" FOREIGN KEY ("item_id")
949
    REFERENCES "items"("item_id")
950
    ON DELETE CASCADE
951
    ON UPDATE NO ACTION
952
    NOT DEFERRABLE,
953
  CONSTRAINT "related_items_related_item_id_fkey" FOREIGN KEY ("related_item_id")
954
    REFERENCES "items"("item_id")
955
    ON DELETE CASCADE
956
    ON UPDATE NO ACTION
957
    NOT DEFERRABLE
958
);
959
</com:TTextHighlighter>
960
 
961
<p id="710040" class="block-content">The association table name in third element of the relationship array may
962
contain the foreign table column names. The columns defined in the association
963
table must also be defined in the record class (e.g. the <tt>$related_item_id</tt> property
964
corresponds to the <tt>related_item_id</tt> column in the <tt>related_items</tt> table).
965
</p>
966
<com:TTextHighlighter Language="php" CssClass="source block-content">
967
class Item extends TActiveRecord
968
{
969
    const TABLE="items";
970
    public $item_id;
971
    public $details;
972
 
973
    //additional foreign item id defined in the association table
974
    public $related_item_id;
975
    public $related_items=array();    // this declaration is no longer needed since v3.1.2
976
 
977
    public static $RELATIONS=array
978
    (
979
        'related_items' => array(self::MANY_TO_MANY,
980
            'Item', 'related_items.related_item_id'),
981
    );
982
}
983
</com:TTextHighlighter>
984
<div class="tip"><b class="note">Tip:</b>
985
Compound keys in the foreign table can
986
be specified as comma separated values between brackets. E.g.
987
<tt>'related_items.(id1,id2)'</tt>.
988
</div>
989
 
990
<!---
991
<h2 id="142014">Adding/Removing/Updating Related Objects</h2>
992
 
993
<p id="710041" class="block-content">Related objects can be simply inserted/updated by first adding those related objects to
994
the current source object (i.e. the object currently been worked on) and then call
995
the <tt>save()</tt> method on the source object. The related object's references
996
and the association reference (if required) will be added and/or updated.
997
For example, to add two new players to the team (assuming that 'Team A' exists), we can simply do the following.
998
</p>
999
 
1000
<com:TTextHighlighter Language="php" CssClass="source block-content">
1001
$team = TeamRecord::finder()->findByPk('Team A');
1002
$team->players[] = new PlayerRecord(array('age'=>20));
1003
$team->players[] = new PlayerRecord(array('age'=>25));
1004
$team->save();
1005
</com:TTextHighlighter>
1006
<p id="710042" class="block-content">
1007
Since the <tt>TeamRecord</tt> class contains a <b>has many</b> relationship with the <tt>PlayerRecord</tt>,
1008
then saving a <tt>TeamRecord</tt> object will also update the corresponding foreign objects in <tt>$players</tt> array.
1009
That is, the objects in <tt>$players</tt> are inserted/updated in the database and the
1010
<tt>$team_name</tt> property of those objects will contain the foreign key value that corresponds to the <tt>$team</tt> object's primary key value.
1011
</p>
1012
 
1013
<p id="710043" class="block-content">To delete a particular foreign object (or any Active Record object), simply call
1014
the object's <tt>delete()</tt> method. You may setup the database table's foreign key constraints such that
1015
when deleting a particular data in the database it will delete the referenced data as well (it may also be achieved using database
1016
triggers). E.g. such as having a "<tt>ON DELETE CASCADE</tt>" constraint.
1017
Deleting foreign objects by either setting the property value to null or removing the object from an array will <b>NOT</b>
1018
remove the corresponding data in the database.
1019
</p>
1020
 
1021
<p id="710044" class="block-content">To remove associations for the many-to-many relationships via an association table, an Active Record
1022
that corresponds to the association table can be used. Then the association can be removed by calling the <tt>deleteByPk()</tt> method, for example:
1023
</p>
1024
<com:TTextHighlighter Language="php" CssClass="source block-content">
1025
PlayerSkillAssocation::finder()->deleteByPk(array('fk1','fk2'));
1026
//where 'fk1' is the primary key value of a player
1027
// and 'fk2' is the primary key value of a skill
1028
</com:TTextHighlighter>
1029
--->
1030
 
1031
<h2 id="142015">Lazy Loading Related Objects</h2>
1032
 
1033
<div class="note"><b class="note">Note:</b>
1034
Implicitly declared related properties introduced in version 3.1.2 automatically have lazy
1035
loading feature. Therefore, the lazy loading technique described in the following is no longer
1036
needed in most of the cases, unless you want to manipulate the related objects through getter/setter.
1037
</div>
1038
 
1039
<p id="710045" class="block-content">Using the <tt>with_xxx()</tt> methods will load the relationship record on demand. Retrieving the
1040
related record using lazy loading (that is, only when those related objects are accessed) can be
1041
achieved by using a feature of the <tt>TComponent</tt> that provides accessor methods. In particular,
1042
we define a pair of getter and setter methods where the getter method will retrieve the relationship
1043
conditionally. The following example illustrates that the <tt>PlayerRecord</tt> can retrieve its
1044
<tt>$skills</tt> foreign objects conditionally.
1045
</p>
1046
<com:TTextHighlighter Language="php" CssClass="source block-content">
1047
class PlayerRecord extends BaseFkRecord
1048
{
1049
    //... other properties and methods as before
1050
 
1051
    private $_skills; //change to private and default as null
1052
 
1053
    public function getSkills()
1054
    {
1055
        if($this->_skills===null && $this->player_id !==null)
1056
        {
1057
            //lazy load the skill records
1058
            $this->setSkills($this->withSkills()->findByPk($this->player_id)->skills);
1059
        }
1060
        else if($this->_skills===null)
1061
        {
1062
            //create new TList;
1063
            $this->setSkills(new TList());
1064
        }
1065
 
1066
        return $this->_skills;
1067
    }
1068
 
1069
    public function setSkills($value)
1070
    {
1071
        $this->_skills = $value instanceof TList ? $value : new TList($value);
1072
    }
1073
}
1074
</com:TTextHighlighter>
1075
<p id="710046" class="block-content">We first need to change the <tt>$skills=array()</tt> declaration to a private property
1076
<tt>$_skills</tt> (notice the underscore) and set it to null instead. This allows us
1077
to define the <tt>skills</tt> property using getter/setter methods
1078
(see <a href="?page=Fundamentals.Components">Components</a> for details). The <tt>getSkills()</tt>
1079
getter method for the <tt>skills</tt> property will lazy load the corresponding skills foreign record
1080
when it is used as follows. Notice that we only do a lazy load when its <tt>$player_id</tt> is
1081
not null (that is, when the record is already fetched from the database or player id was already set).
1082
</p>
1083
<com:TTextHighlighter Language="php" CssClass="source block-content">
1084
$player = PlayerRecord::finder()->findByPk(1);
1085
var_dump($player->skills); //lazy load it on first access
1086
var_dump($player->skills[0]); //already loaded skills property
1087
$player->skills[] = new SkillRecord(); //add skill
1088
</com:TTextHighlighter>
1089
 
1090
<p id="710047" class="block-content">The <tt>setSkills()</tt> ensures that the <tt>skills</tt> property will always be a TList.
1091
Using a TList allows us to set the elements of the <tt>skills</tt> property as if they were
1092
arrays. E.g. <tt>$player->skills[] = new SkillRecord()</tt>. If <tt>array</tt> was used, a PHP error
1093
will be thrown.
1094
</p>
1095
 
1096
<h2>Column Mapping</h2>
1097
<p>
1098
Since v3.1.1, Active Record starts to support column mapping. Column mapping allows developers
1099
to address columns in Active Record using a more consistent naming convention. In particular,
1100
using column mapping, one can access a column using whatever name he likes, rather than limited by
1101
the name defined in the database schema.
1102
</p>
1103
<p>
1104
To use column mapping, declare a static array named <tt>COLUMN_MAPPING</tt> in the Active Record class.
1105
The keys of the array are column names (called <i>physical column names</i>) as defined in the database
1106
schema, while the values are corresponding property names (called <i>logical column names</i>) defined
1107
in the Active Record class. The property names can be either public class member variable names or
1108
component property names defined via getters/setters. If a physical column name happens to be the same
1109
as the logical column name, they do not need to be listed in <tt>COLUMN_MAPPING</tt>.
1110
</p>
1111
<com:TTextHighlighter Language="php" CssClass="source block-content">
1112
class UserRecord extends TActiveRecord
1113
{
1114
	const TABLE='users';
1115
	public static $COLUMN_MAPPING=array
1116
	(
1117
		'user_id'=>'id',
1118
		'email_address'=>'email',
1119
		'first_name'=>'firstName',
1120
		'last_name'=>'lastName',
1121
	);
1122
	public $id;
1123
	public $username; // the physical and logical column names are the same
1124
	public $email;
1125
	public $firstName;
1126
	public $lastName;
1127
	//....
1128
}
1129
</com:TTextHighlighter>
1130
<p>
1131
With the above column mapping, we can address <tt>first_name</tt> using <tt>$userRecord->firstName</tt>
1132
instead of <tt>$userRecord->first_name</tt>. This helps separation of logic and model.
1133
</p>
1134
 
1135
<h2 id="138054">References</h2>
1136
<ul id="u3" class="block-content">
1137
    <li>Fowler et. al. <i>Patterns of Enterprise Application Architecture</i>,
1138
    Addison Wesley, 2002.</li>
1139
	<li>B. Venners with B. Eckel. <i><a href="http://www.artima.com/intv/abstract3.html">Inappropriate Abstractions - A Conversation with Anders Hejlsberg, Part VI.</a></i>
1140
	Artima Developer, 2003.
1141
	</li>
1142
 
1143
</ul>
1144
 
1145
<div class="last-modified">$Id: ActiveRecord.page 2366 2008-01-14 08:28:23Z aztech $</div></com:TContent>