summaryrefslogtreecommitdiff
path: root/demos/quickstart/protected/pages/Database/ActiveRecord.page
blob: 1e3c69c5d41a624d1326bee839fec17a71c02503 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
<com:TContent ID="body" >
<!-- $Id $ -->
<h1 id="138046">Active Record</h1>
<com:SinceVersion Version="3.1a" />
<p id="690478" class="block-content">Active Records are objects that wrap a row in a database table or view,
    encapsulates the database access and adds domain logic on that data.
    The basics of an Active Record is a business object class, e.g., a 
    <tt>Products</tt> class,  that match very closely the record structure
    of an underlying database table. Each Active Record will be responsible for
    saving and loading data to and from the database. </p>
<div class="info"><b class="note">Info:</b>
    The data structure of an Active Record should  match exactly that of a table 
    in the database.
    Each field in the class must correspond to one column in the table.
</div>

<h2 id="138047">When to Use It</h2>
<p id="690479" class="block-content">Active Record is a good choice for domain logic that isn't too complex, 
    such as creates, reads, updates, and deletes. Derivations and validations
    based on a single record work well in this structure. Active Record has the
    primary advantage of simplicity. It's easy to build 
    Active Records, and they are easy to understand.</p>

    <p id="690480" class="block-content">However, as your business logic grows in complexity, you'll soon want 
    to use your object's direct relationships, collections, inheritance, and so
    forth. These don't map easily onto Active Record, and adding them piecemeal 
    gets very messy.
    Another argument against Active Record is the fact that it couples the object 
    design to the database design. This makes it more difficult to refactor as a project goes forward.</p>
    
    <p id="690481" class="block-content">The alternative is to use a Data Mapper that separates the roles of the
        business object and how these objects are stored.       
        Prado provides a complimentary choice between Active Record and 
        <a href="?page=Database.SqlMap">SqlMap Data Mapper</a>. 
        A SqlMap Data Mapper can be used to load Active Record objects, in turn, these
        Active Record objects can be used to update the database. 
        The "relationship" between Active Records and <a href="?page=Database.SqlMap">SqlMap</a> is illustrated in the
    following diagram. More details regarding the SqlMap Data Mapper can be found in
    the <a href="http://www.pradosoft.com/demos/sqlmap/">SqlMap Manual</a>.
    <img src=<%~ sqlmap_active_record.png %> alt="Active Records and SqlMap DataMapper" id="fig:diagram.png" class="figure"/>
    </p>
    
    <p id="690482" class="block-content">
        The Active Record class has methods that do the following:
    </p>
    <ul id="u1" class="block-content">
        <li>Construct an instance of the Active Record from a SQL result set row.</li>
        <li>Construct a new instance for later insertion into the table.</li>
        <li>Finder methods to wrap commonly used SQL queries and return Active Record objects.</li>
        <li>Update existing records and insert new records into the database.</li>
    </ul>
<h2>Database Supported</h2>
<p id="p1" class="block-content">
The Active Record implementation utilizes the <a href="?page=Database.DAO">Prado DAO</a> classes for data access.   
The current Active Record implementation supports the following database. 
</p>
<ul>
    <li><a href="http://www.mysql.com">MySQL 4.1 or later</a></li>
    <li><a href="http://www.postgres.com">Postgres SQL 7.3 or later</a></li>
    <li><a href="http://www.sqlite.org">SQLite 2 and 3</a></li>
    <li><a href="#">MS SQL 2000 or later</a></li>
</ul>
<p>Support for other databases can be provided when there are sufficient demand.</p>

<h1 id="138048">Defining an Active Record</h1>
<p id="690483" class="block-content">Let us
    consider the following "users" table that contains two columns named "username" and "email", 
    where "username" is also the primary key. 
<com:TTextHighlighter Language="sql" CssClass="source block-content" id="code_690147">
CREATE TABLE users
(
    username VARCHAR( 20 ) NOT NULL ,
    email VARCHAR( 200 ) ,
    PRIMARY KEY ( username )
);
</com:TTextHighlighter>
</p>
<p id="690484" class="block-content">Next we define our Active Record class that corresponds to the "users" table.
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690148">
class UserRecord extends TActiveRecord
{
    const TABLE='users'; //table name 

    public $username; //the column named "username" in the "users" table
    public $email;
    
    /**
     * @return TActiveRecord active record finder instance
     */
    public static function finder($className=__CLASS__)
    {
        return parent::finder($className);
    }
}
</com:TTextHighlighter>
</p>
<p id="690485" class="block-content">Each property of the <tt>UserRecord</tt> class must correspond to a
    column with the same name in the "users" table. The class constant
    <tt>TABLE</tt> is optional when the class name is the same as
    the table name in the database, otherwise <tt>TABLE</tt> must
    specify the table name that corresponds to your Active Record class.
</p>

<div class="tip"><b class="note">Tip:</b>
You may specify qualified table names. E.g. for MySQL, <tt>TABLE = "`database1`.`table1`"</tt>.
</div>

<p class="block-content" id="ar_as_component">
    Since <tt>TActiveRecord</tt> extends <tt>TComponent</tt>, setter and
    getter methods can be defined to allow control over how variables
    are set and returned. For example, adding a <tt>$level</tt> property to the UserRecord class:
</p>
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690149">
class UserRecord extends TActiveRecord {
    ... //existing definitions as above
    
    private $_level;
    public function setLevel($value) {
        $this->_level=TPropertyValue::ensureInteger($value,0);
    }
    public function getLevel($value){
        return $this->_level;
    }
}
</com:TTextHighlighter>

<div class="info"><b class="note">Info:</b>
<tt>TActiveRecord</tt> can also work with database views by specifying the constant <tt>TABLE</tt>
corresponding to the view name. However, objects returned
from views are read-only, calling the <tt>save()</tt> or <tt>delete()</tt> method
will raise an exception. 
</div>

<p id="690486" class="block-content">
    The static method <tt>finder()</tt> returns an <tt>UserRecord</tt> instance
    that can be used to load records from the database. The loading of records
    using the finer methods is discuss a little later. The <tt>TActiveRecord::finder()</tt>
    static method takes the name of the current Active Record class as parameter.
</p>

<h2 id="138049">Setting up a database connection</h2>
<p id="690487" class="block-content">
    A default database connection for Active Record can be set as follows.
    See <a href="?page=Database.DAO">Establishing Database Connection</a> for
    futher details regarding creation of database connection in general.
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690150">
//create a connection and give it to the Active Record manager.
$dsn = 'pgsql:host=localhost;dbname=test'; //Postgres SQL
$conn = new TDbConnection($dsn, 'dbuser','dbpass');
TActiveRecordManager::getInstance()->setDbConnection($conn);
</com:TTextHighlighter> 
</p>

<p id="690488" class="block-content">
    The default database connection can also be configured using a <tt>&lt;module&gt;</tt>
    tag in the <a href="?page=Configurations.AppConfig">application.xml</a> 
    or <a href="?page=Configurations.PageConfig">config.xml</a> as follows.
<com:TTextHighlighter Language="xml" CssClass="source block-content" id="code_690151">
<modules>
  <module class="System.Data.ActiveRecord.TActiveRecordConfig" EnableCache="true">
    <database ConnectionString="pgsql:host=localhost;dbname=test"
        Username="dbuser" Password="dbpass" />
  </module>
</modules>  
</com:TTextHighlighter> 
<div class="tip"><b class="note">Tip:</b>
    The <tt>EnableCache</tt> attribute when set to "true" will cache the table
    meta data, that is, the table columns names, indexes and constraints are
    saved in the cache and reused. You must clear or disable the cache if you
    wish to see chanages made to your table definitions. A <a href="?page=Advanced.Performance#6402">cache
    module</a> must also be defined for the cache to function.
</div>
</p>

<p id="690489" class="block-content">A <tt>ConnectionID</tt> property can be specified with value corresponding
    to another <tt>TDataSourceConfig</tt> module configuration's ID value. This allows
    the same database connection to be used in other modules such as <a href="?page=Database.SqlMap">SqlMap</a>.
<com:TTextHighlighter Language="xml" CssClass="source block-content" id="code_690152">
<modules>
  <module class="System.Data.TDataSourceConfig" id="db1">
    <database ConnectionString="pgsql:host=localhost;dbname=test"
        Username="dbuser" Password="dbpass" />
  </module>

  <module class="System.Data.ActiveRecord.TActiveRecordConfig" 
        ConnectionID="db1" EnableCache="true"  />

  <module class="System.Data.SqlMap.TSqlMapConfig"
        ConnectionID="db1"  ... />
</modules>  
</com:TTextHighlighter>     
</p>

<h2 id="138050">Loading data from the database</h2>
<p id="690490" class="block-content">
    The <tt>TActiveRecord</tt> class provides many convenient methods to find
    records from the database. The simplest is finding records by matching primary keys.
    See the <com:DocLink ClassPath="System.Data.ActiveRecord.TActiveRecord" /> for
    more details.
</p>
    <h3 id="138055"><tt>findByPk()</tt></h3>
    <p id="690491" class="block-content">Finds one record using only the primary key or composite primary keys.
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690153">
$finder = UserRecord::finder();
$user = $finder->findByPk($primaryKey);

//when the table uses composite keys
$record = $finder->findByPk($key1, $key2, ...);
$record = $finder->findByPk(array($key1, $key2,...));
</com:TTextHighlighter>
</p>

    <h3 id="138056"><tt>findAllByPks()</tt></h3>
    <p id="690492" class="block-content">Finds multiple records using a list of primary keys or composite primary keys.
The following are equivalent for scalar primary keys (primary key consisting of only one column/field).
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690154">
$finder = UserRecord::finder();
$users = $finder->findAllByPk($key1, $key2, ...);
$users = $finder->findAllByPk(array($key1, $key2, ...));
</com:TTextHighlighter>
The following are equivalent for composite keys.
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690155">
//when the table uses composite keys
$record = $finder->findAllByPks(array($key1, $key2), array($key3, $key4), ...);

$keys = array(  array($key1, $key2), array($key3, $key4), ... );
$record = $finder->findAllByPks($keys);

</com:TTextHighlighter>
</p>


<h3 id="138057"><tt>find()</tt></h3>
<p id="690493" class="block-content">Finds <b>one single record</b> that matches the criteria. The criteria
    can be a partial SQL string or a <tt>TActiveRecordCriteria</tt> object.</p>
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690156">
$finder = UserRecord::finder();

//:name and :pass are place holders for specific values of $name and $pass
$finder->find('username = :name AND password = :pass',
                          array(':name'=>$name, ':pass'=>$pass));

//using position place holders
$finder->find('username = ? AND password = ?', array($name, $pass));
//same as above
$finder->find('username = ? AND password = ?', $name, $pass);

//$criteria is of TActiveRecordCriteria
$finder->find($criteria); //the 2nd parameter for find() is ignored.
</com:TTextHighlighter>

<p id="690494" class="block-content">The <tt>TActiveRecordCriteria</tt> class has the following properties:
</p>
    <ul id="u2" class="block-content">
        <li><tt>Parameters</tt> -- name value parameter pairs.</li>
        <li><tt>OrdersBy</tt> -- column name and ordering pairs.</li>
        <li><tt>Condition</tt> -- parts of the WHERE SQL conditions.</li>
        <li><tt>Limit</tt> -- maximum number of records to return.</li>
        <li><tt>Offset</tt> -- record offset in the table.</li>
    </ul>

<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690157">
$criteria = new TActiveRecordCriteria;
$criteria->Condition = 'username = :name AND password = :pass';
$criteria->Parameters[':name'] = 'admin';
$criteria->Parameters[':pass'] = 'prado';
$criteria->OrdersBy['level'] = 'desc';
$criteria->OrdersBy['name'] = 'asc';
$criteria->Limit = 10;
$criteria->Offset = 20;
</com:TTextHighlighter>

<h3 id="138058"><tt>findAll()</tt></h3>
<p id="690495" class="block-content">Same as <tt>find()</tt> but returns an array of objects.</p>

<h3 id="138059"><tt>findBy*()</tt> and <tt>findAllBy*()</tt></h3>
<p id="690496" class="block-content">Dynamic find method using parts of method name as search criteria.
Method names starting with <tt>findBy</tt> return 1 record only.
Method names starting with <tt>findAllBy</tt> return an array of records.
The condition is taken as part of the method name after <tt>findBy</tt> or <tt>findAllBy</tt>.

The following blocks of code are equivalent:
</p>
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690158">
$finder->findByName($name)
$finder->find('Name = ?', $name);
</com:TTextHighlighter>

<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690159">
$finder->findByUsernameAndPassword($name,$pass);
$finder->findBy_Username_And_Password($name,$pass);
$finder->find('Username = ? AND Password = ?', $name, $pass);
</com:TTextHighlighter>

<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690160">
$finder->findAllByAge($age);
$finder->findAll('Age = ?', $age);
</com:TTextHighlighter>
    
<div class="tip"><b class="note">Tip:</b>
You may also use <tt>OR</tt> as a condition in the dynamic methods.
</div>
    
<h3 id="138060"><tt>findBySql()</tt></h3>
<p id="690497" class="block-content">Finds records using full SQL, returns corresponding array of record objects.</p>

<h3 id="138061"><tt>count()</tt></h3>
<p id="690498" class="block-content">Find the number of matchings records.</p>

<h2 id="138051">Inserting and updating records</h2>
<p id="690499" class="block-content">
Add a new record using TActiveRecord is very simple, just create a new Active
Record object and call the <tt>save()</tt> method. E.g.
</p>
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690161">
$user1 = new UserRecord();
$user1->username = "admin";
$user1->email = "admin@example.com";
$user1->save(); //insert a new record

$data = array('username'=>'admin', 'email'=>'admin@example.com');
$user2 = new UserRecord($data); //create by passing some existing data
$user2->save(); //insert a new record
</com:TTextHighlighter>
<div class="tip"><b class="note">Tip:</b>
The objects are update with the primary key of those the tables that contains 
definitions that automatically creates a primary key for the newly insert records.
For example, if you insert a new record into a MySQL table that has columns
defined with "autoincrement", the Active Record objects will be updated with the new 
incremented values.</div>

<p id="690500" class="block-content">
To update a record in the database, just change one or more properties of 
the Active Record object that has been loaded from the database and then
call the <tt>save()</tt> method.    

<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690162">
$user = UserRecord::finder()->findByName('admin');
$user->email="test@example.com"; //change property
$user->save(); //update it.
</com:TTextHighlighter>
</p>

<p>
Active Record objects have a simple life-cycle illustrated in the following diagram.
</p>
<img src=<%~ object_states.png %> alt="Active Records Life Cycle" id="fig:cycle.png" class="figure"/>
<p id="690501" class="block-content">
We see that new TActiveRecord objects are created by either using one of the <tt>find*()</tt>
methods or using creating a new instance by using PHP's <tt>new</tt> keyword. Objects
created by a <tt>find*()</tt> method starts with <tt>clean</tt> state. New instance of 
TActiveRecord created other than by a <tt>find*()</tt> method starts with <tt>new</tt> state.
When ever you 
call the <tt>save()</tt> method on the TActiveRecord object, the object enters the <tt>clean</tt>
state. Objects in the <tt>clean</tt> becomes <tt>dirty</tt> whenever one of more of its
internal states are changed. Calling the <tt>delete()</tt> method on the object
ends the object life-cycle, no futher actions can be performed on the object.
</p>

<h2 id="138052">Deleting existing records</h2>
<p id="690502" class="block-content">
    To delete an existing record that is already loaded, just call the <tt>delete()</tt> method.
    You can also delete records in the database by primary keys without
    loading any records using the <tt>deleteByPk()</tt> method. 
    For example, to delete one or records with tables having a scalar primary key.
</p>
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690163">
$finder->deleteByPk($primaryKey); //delete 1 record
$finder->deleteByPk($key1,$key2,...); //delete multiple records
$finder->deleteByPk(array($key1,$key2,...)); //delete multiple records
</com:TTextHighlighter>

<p id="690503" class="block-content">
For composite primary keys (determined automatically from the table definitions):
</p>
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690164">
$finder->deleteByPk(array($key1,$key2)); //delete 1 record

//delete multiple records
$finder->deleteByPk(array($key1,$key2), array($key3,$key4),...);

//delete multiple records
$finder->deleteByPk(array( array($key1,$key2), array($key3,$key4), .. ));
</com:TTextHighlighter>

<h3 id="138052a"><tt>deleteAll()</tt> and <tt>deleteBy*()</tt></h3>
<p id="690502a" class="block-content">
To delete by a criteria, use <tt>deleteAll($criteria)</tt> and <tt>deleteBy*()</tt>
with similar synatx to <tt>findAll($criteria)</tt> and <tt>findAllBy*()</tt> as
described above.
</p>
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690163a">
//delete all records with matching Name
$finder->deleteAll('Name = ?', $name);
$finder->deleteByName($name);

//delete by username and password
$finder->deleteBy_Username_And_Password($name,$pass);
</com:TTextHighlighter>

<h2 id="138053">Transactions</h2>
<p id="690504" class="block-content">All Active Record objects contains the property <tt>DbConnection</tt>
    that can be used to obtain a transaction object.
<com:TTextHighlighter Language="php" CssClass="source block-content" id="code_690165">
$finder = UserRecord::finder();
$finder->DbConnection->Active=true; //open if necessary
$transaction = $finder->DbConnection->beginTransaction();
try
{
    $user = $finder->findByPk('admin');
    $user->email = 'test@example.com'; //alter the $user object
    $user->save();
    $transaction->commit();
}
catch(Exception $e) // an exception is raised if a query fails
{
    $transaction->rollBack();
}
</com:TTextHighlighter>

<h1 id="ar_relations">Active Record Relationships</h1>
<p id="690504a" class="block-content">
The Prado Active Record implementation supports the foreign key mappings for database
that supports foreign key contraints. For ActiveRecord relationships to function the
underlying database must support foreign key constraints (e.g. MySQL with InnoDB).
</p>

<p>
In the following sections we shall consider the following table relationships between
<tt>Teams</tt>, <tt>Players</tt>, <tt>Skills</tt> and <tt>Profiles</tt>.
</p>
<img src="<%~ ar_relations.png %>" class="figure" />


<p>The goal is to obtain object models that represents to some degree the entity
relationships in the above figure. 
</p>

<img src="<%~ ar_objects.png %>" class="figure">

<p class="block-content">
There is a mismatch between relationships with objects and table relationships. 
First there's a difference in representation. Objects handle links by storing references 
that are held by the runtime memory-managed environment. Relational databases handle 
links by forming a key into another table. Second, objects can easily use collections 
to handle multiple references from a single field, while normalization forces 
all entity relation links to be single valued. This leads to reversals of the data 
structure between objects and tables. The approach taken in the Prado Active Record 
design is to use the table foreign key constraints to derive object relationships. This implies
that the underlying database must support foreign key constraints.
</p>
<h2>Foreign Key Mapping</h2>
<p class="block-content">The entity relationship between the <tt>Teams</tt> and <tt>Players</tt> table is what is known
as an 1-M relationship. That is, one Team may contain 0 or more Players. In terms of 
object relationships, we say that the <tt>Team</tt> object <b>has many</b> <tt>Player</tt> objects. 
(Notice the reversal of the reversal of the direction of relationships between tables and objects.)
<p>
<h3>Has Many Relationship</h3>
<p>
We model the <tt>Team</tt> object as the following Active Record classes.
</p>
<com:TTextHighlighter Language="php" CssClass="source block-content">
class TeamRecord extends TActiveRecord
{
    const TABLE='Teams';
    public $name;
    public $location;
    
    public $players=array();

    //define the $player member having has many relationship with PlayerRecord
    protected static $RELATIONS=array
    (
        'players' => array(self::HAS_MANY, 'PlayerRecord'),
    );

    public static function finder($className=__CLASS__)
    {
        return parent::finder($className);
    }
}
</com:TTextHighlighter>
<p>
The static <tt>$RELATIONS</tt> property of <tt>TeamRecord</tt> defines that the
property <tt>$players</tt> has many <tt>PlayerRecord</tt>s. Multiple relationships
is permitted by defining each relationship with an entry in the <tt>$RELATIONS</tt>
array where array key for the entry corresponds to the property name.
In <tt>array(self::HAS_MANY, 'PlayerRecord')</tt>, the first element defines the
relationship type, the valid types are <strong><tt>self::HAS_MANY</tt></strong>,
<strong><tt>self::HAS_ONE</tt></strong> and <strong><tt>self::BELONGS_TO</tt></strong>.
The second element is a string <tt>'PlayerRecord'</tt> that corresponds to the
class name of the <tt>PlayerRecord</tt> class.
</p>

<p>
The foreign key constraint of the <tt>Players</tt> table is used to determine the corresponding
<tt>Teams</tt> table's corresponding key names. This is done automatically handled
in Active Record by inspecting the <tt>Players</tt> and <tt>Teams</tt> table definitions.
</p>

<div class="info"><b class="note">Info:</b>
Active Record supports multiple table foreign key relationships with the restiction
that each relationship correponds to a unique table. For example, the <tt>Players</tt>
table may only have one set of foreign key relationship with table <tt>Teams</tt>, it may
have other relationships that corresponds to other tables (including the <tt>Players</tt> table itself).
</div>

<p>The has many relationship is not fetched automatically when you use any of the Active Record finder methods.
You will need to explicitly fetch the related objects as follows. In the code below, both lines 
are equivalent and the method names are case insensitive.
</p>
<com:TTextHighlighter Language="php" CssClass="source block-content">
$team = TeamRecord::finder()->withPlayers()->findAll();
$team = TeamRecord::finder()->with_players()->findAll(); //equivalent
</com:TTextHighlighter Language="php">
<p>
The method <tt>with_xxx()</tt> (where <tt>xxx</tt> is the relationship property
name, in this case, <tt>players</tt>) fetchs the corresponding PlayerRecords using
a second query (not by using a join). The <tt>with_xxx()</tt> accepts the same
arguments as other finder methods of TActiveRecord, e.g. <tt>with_players('age < ?', 35)</tt>.
</p>

<div class="note"><b class="note">Note:</b>
It is essential to understand that the related objects are fetched using additional
queries. The first query fetches the source object, .e.g the <tt>TeamRecord</tt> in the above example code.
A second query is used to fetche the corresponding related <tt>PlayerRecord</tt> objects. 
The usage of the two query is similar to a single query using Left-Outer join with the 
exception that null results on the right table
are not returned. The consequence of using two or more queries is that the aggregates
and other join conditions are not feasible using Active Records. For queries outside the
scope of Active Record the <a href="?page=Database.SqlMap">SqlMap Data Mapper</a> may be considered.
</div>

<h3>Belongs To Relationship</h3>

<com:TTextHighlighter Language="php" CssClass="source block-content">
class PlayerRecord extends TActiveRecord
{
    const TABLE='Players';
    public $player_id;
    public $age;
    public $team_name;

    public $team;
    public $skills=array();
    public $profile;

    protected static $RELATIONS=array
    (
        'team' => array(self::BELONGS_TO, 'TeamRecord'),
        'skills' => array(self::HAS_MANY, 'SkillRecord', 'Player_Skills'),
        'profile' => array(self::HAS_ONE, 'ProfileRecord'),
    );

    public static function finder($className=__CLASS__)
    {
        return parent::finder($className);
    }
}
</com:TTextHighlighter>

<h3>Has One Relationship</h3>

<com:TTextHighlighter Language="php" CssClass="source block-content">
class ProfileRecord extends TActiveRecord
{
    const TABLE='Profiles';
    public $player_id;
    public $salary;

    public $player;

    protected static $RELATIONS=array
    (
        'player' => array(self::BELONGS_TO, 'PlayerRecord'),
    );

    public static function finder($className=__CLASS__)
    {
        return parent::finder($className);
    }
}
</com:TTextHighlighter>


<h2>Association Table Mapping</h2>

<com:TTextHighlighter Language="php" CssClass="source block-content">
class SkillRecord extends TActiveRecord
{
    const TABLE='Skills';
    public $skill_id;
    public $name;

    public $players=array();

    protected static $RELATIONS=array
    (
        'players' => array(self::HAS_MANY, 'PlayerRecord', 'Player_Skills'),
    );

    public static function finder($className=__CLASS__)
    {
        return parent::finder($className);
    }
}
</com:TTextHighlighter>

<h2 id="138054">References</h2>
<ul id="u3" class="block-content">
    <li>Fowler et. al. <i>Patterns of Enterprise Application Architecture</i>,
    Addison Wesley, 2002.</li>
</ul>

<div class="last-modified">$Id$</div></com:TContent>