-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathORM.php
1307 lines (1128 loc) · 41.8 KB
/
ORM.php
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* [Object Relational Mapping][ref-orm] (ORM) is a method of abstracting database
* access to standard PHP calls. All table rows are represented as model objects,
* with object properties representing row data. ORM in Kohana generally follows
* the [Active Record][ref-act] pattern.
*
* [ref-orm]: http://wikipedia.org/wiki/Object-relational_mapping
* [ref-act]: http://wikipedia.org/wiki/Active_record
*
* @package ORM
* @author Espen Volden
*/
class AetherORM {
// Current relationships
protected $hasOne = array();
protected $belongsTo = array();
protected $hasMany = array();
protected $hasAndBelongsToMany = array();
// Relationships that should always be joined
protected $loadWith = array();
// Current object
protected $object = array();
protected $changed = array();
protected $related = array();
protected $loaded = false;
protected $saved = false;
protected $sorting;
// Related objects
protected $objectRelations = array();
protected $changedRelations = array();
// Model table information
protected $objectName;
protected $objectPlural;
protected $tableName;
protected $tableColumns;
protected $ignoredColumns;
protected $columnAlias;
// Table primary key and value
protected $primaryKey = 'id';
protected $primaryVal = 'name';
// Array of foreign key name overloads
protected $foreignKey = array();
// Model configuration
protected $tableNamesPlural = true;
protected $reloadOnWakeup = true;
// Database configuration
protected $db = 'default';
protected $dbApplied = array();
// With calls already applied
protected $withApplied = array();
// Stores column information for ORM models
protected static $columnCache = array();
/**
* Creates and returns a new model.
*
* @param string $model model name
* @param mixed $id parameter for find()
* @return AetherORM
*/
public static function factory($model, $id = NULL) {
// Set class name
$model = ucfirst($model) . 'Model';
return new $model($id);
}
/**
* Prepares the model database connection and loads the object.
*
* @param mixed parameter for find or object to load
* @return void
*/
public function __construct($id = NULL) {
// Set the object name and plural name
$this->objectName = strtolower(substr(get_class($this), 0, -5));
$this->objectPlural = Inflector::plural($this->objectName);
if (!isset($this->sorting)) {
// Default sorting
$this->sorting = array($this->primaryKey => 'asc');
}
// Initialize database
$this->__initialize();
// Clear the object
$this->clear();
if (is_object($id)) {
// Load an object
$this->loadValues((array)$id);
}
elseif (!empty($id)) {
// Find an object
$this->find($id);
}
}
/**
* Prepares the model database connection, determines the table name,
* and loads column information.
*
* @return void
*/
public function __initialize() {
if (!is_object($this->db)) {
// Get database instance
$this->db = AetherDatabase::instance($this->db);
}
if (empty($this->tableName)) {
// Table name is the same as the object name
$this->tableName = $this->objectName;
if ($this->tableNamesPlural === true) {
// Make the table name plural
$this->tableName = Inflector::plural($this->tableName);
}
}
if (is_array($this->ignoredColumns)) {
// Make the ignored columns mirrored = mirrored
$this->ignoredColumns = array_combine($this->ignoredColumns,
$this->ignoredColumns);
}
// Set column aliases and working table
if ($this->columnAlias !== NULL && is_array($this->columnAlias) &&
!empty($this->columnAlias)) {
$this->db->setColumnAlias($this->tableName, $this->columnAlias);
$this->db->setWorkingTable($this->tableName);
}
// Its not possible to have an alias for the id and to set primaryKey to
// be the column
if ($this->db->aliasColumn($this->primaryKey, false) !=
$this->primaryKey) {
throw new Exception('Its impossible to set the primaryKey to '.
'something different then the alias');
}
// Load column information
$this->reloadColumns();
}
/**
* Allows serialization of only the object data and state, to prevent
* "stale" objects being unserialized, which also requires less memory.
*
* @return array
*/
public function __sleep() {
// Store only information about the object
return array('objectName', 'object', 'changed', 'loaded', 'saved',
'sorting');
}
/**
* Prepares the database connection and reloads the object.
*
* @return void
*/
public function __wakeup() {
// Initialize database
$this->__initialize();
if ($this->reloadOnWakeup === true) {
// Reload the object
$this->reload();
}
}
/**
* Handles pass-through to database methods. Calls to query methods
* (query, get, insert, update) are not allowed. Query builder methods
* are chainable.
*
* @param string $method method name
* @param array $args method arguments
* @return mixed
*/
public function __call($method, array $args) {
if (method_exists($this->db, $method)) {
if (in_array($method, array('query', 'get', 'insert', 'update', 'delete')))
throw new DatabaseException('Query methods not allowed in ORM');
// Method has been applied to the database
$this->dbApplied[$method] = $method;
// Number of arguments passed
$numArgs = count($args);
if ($method === 'select' && $numArgs > 3) {
// Call select() manually to avoid call_user_func_array
$this->db->select($args);
}
else {
// We use switch here to manually call the database methods. This is
// done for speed: call_user_func_array can take over 300% longer to
// make calls. Most database methods are 4 arguments or less, so this
// avoids almost any calls to call_user_func_array.
switch ($numArgs) {
case 0:
if (in_array($method, array('openParen', 'closeParen',
'enableCache', 'disableCache'))) {
// Should return AetherORM, not Database
$this->db->$method();
}
else {
// Support for things like reset_select, reset_write, list_tables
return $this->db->$method();
}
break;
case 1:
$this->db->$method($args[0]);
break;
case 2:
$this->db->$method($args[0], $args[1]);
break;
case 3:
$this->db->$method($args[0], $args[1], $args[2]);
break;
case 4:
$this->db->$method($args[0], $args[1], $args[2], $args[3]);
break;
default:
// Here comes the snail...
call_user_func_array(array($this->db, $method), $args);
break;
}
}
return $this;
}
else {
throw new Exception('invalid method: ' . $method . ' in ' .
get_class($this));
}
}
/**
* Handles retrieval of all model values, relationships, and metadata.
*
* @param string $column column name
* @return mixed
*/
public function __get($column) {
if (array_key_exists($column, $this->object)) {
return $this->object[$column];
}
elseif (array_key_exists($column, $this->related)) {
return $this->related[$column];
}
elseif ($column === 'primaryKeyValue') {
return $this->object[$this->primaryKey];
}
elseif ($model = $this->relatedObject($column)) {
// This handles the has_one and belongs_to relationships
if (in_array($model->objectName, $this->belongsTo) ||
!array_key_exists($this->foreignKey($column), $model->object)) {
// Foreign key lies in this table
//(this model belongs_to target model) OR an invalid has_one relationship
$where = array($model->tableName .'.'. $model->primaryKey =>
$this->object[$this->foreignKey($column)]);
}
else {
// Foreign key lies in the target table (this model has_one target model)
$where = array($this->foreignKey($column, $model->tableName) =>
$this->primaryKeyValue);
}
// one<>alias:one relationship
return $this->related[$column] = $model->find($where);
}
elseif (isset($this->hasMany[$column])) {
// Load the "middle" model
$through = AetherORM::factory(Inflector::singular(
$this->hasMany[$column]));
// Load the "end" model
$model = AetherORM::factory(Inflector::singular($column));
// Join ON target model's primary key set to 'through' model's foreign key
// User-defined foreign keys must be defined in the 'through' model
$joinTable = $through->tableName;
$joinCol1 = $through->foreignKey($model->objectName, $joinTable);
$joinCol2 = $model->tableName .'.'. $model->primaryKey;
// one<>alias:many relationship
return $this->related[$column] = $model
->join($joinTable, $joinCol1, $joinCol2)
->where($through->foreignKey($this->objectName, $joinTable),
$this->object[$this->primaryKey])->findAll();
}
elseif (in_array($column, $this->hasMany)) {
// one<>many relationship
$model = AetherORM::factory(Inflector::singular($column));
return $this->related[$column] = $model
->where($this->foreignKey($column, $model->tableName),
$this->object[$this->primaryKey])->findAll();
}
elseif (in_array($column, $this->hasAndBelongsToMany)) {
// Load the remote model, always singular
$model = AetherORM::factory(Inflector::singular($column));
if ($this->has($model, true)) {
// many<>many relationship
return $this->related[$column] = $model
->in($model->tableName .'.'. $model->primaryKey,
$this->changedRelations[$column])->findAll();
}
else {
// empty many<>many relationship
return $this->related[$column] = $model
->where($model->tableName .'.'. $model->primaryKey, NULL)
->findAll();
}
}
elseif (isset($this->ignoredColumns[$column])) {
return NULL;
}
elseif (in_array($column, array(
'objectName', 'objectPlural', // Object
'primaryKey', 'primaryVal', 'tableName', 'tableColumns', // Table
'loaded', 'saved', // Status
'hasOne', 'belongsTo', 'hasMany', 'hasAndBelongsToMany',
'loadWith' // Relationships
))) {
// Model meta information
return $this->$column;
}
else {
throw new Exception('invalid property: ' . $column .' '.
get_class($this));
}
}
/**
* Handles setting of all model values, and tracks changes between values.
*
* @param string $column column name
* @param mixed $value column value
* @return void
*/
public function __set($column, $value) {
$this->__initialize();
if (isset($this->ignoredColumns[$column])) {
return NULL;
}
elseif (isset($this->object[$column]) || array_key_exists($column, $this->object)) {
if (isset($this->tableColumns[$column])) {
// Data has changed
$this->changed[$column] = $column;
// Object is no longer saved
$this->saved = false;
}
$this->object[$column] = $this->loadType($column, $value);
}
elseif (in_array($column, $this->hasAndBelongsToMany) && is_array($value)) {
// Load relations
$model = AetherORM::factory(Inflector::singular($column));
if (!isset($this->objectRelations[$column])) {
// Load relations
$this->has($model);
}
// Change the relationships
$this->changedRelations[$column] = $value;
if (isset($this->related[$column])) {
// Force a reload of the relationships
unset($this->related[$column]);
}
}
else {
throw new Exception('invalid property: ' . $column .' '.
get_class($this));
}
}
/**
* Checks if object data is set.
*
* @param string $column column name
* @return boolean
*/
public function __isset($column) {
return (isset($this->object[$column]) || isset($this->related[$column]));
}
/**
* Unsets object data.
*
* @param string $column column name
* @return void
*/
public function __unset($column) {
unset($this->object[$column], $this->changed[$column],
$this->related[$column]);
}
/**
* Displays the primary key of a model when it is converted to a string.
*
* @return string
*/
public function __toString() {
return (string)$this->object[$this->primaryKey];
}
/**
* Returns the values of this object as an array.
*
* @return array
*/
public function asArray() {
$object = array();
foreach ($this->object as $key => $val) {
// Reconstruct the array (calls __get)
$object[$key] = $this->$key;
}
return $object;
}
/**
* Binds another one-to-one object to this model. One-to-one objects
* can be nested using 'object1:object2' syntax
*
* @param string $targetPath
* @return void
*/
public function with($targetPath) {
if (isset($this->withApplied[$targetPath])) {
// Don't join anything already joined
return $this;
}
// Split object parts
$objects = explode(':', $targetPath);
$target = $this;
foreach ($objects as $object) {
// Go down the line of objects to find the given target
$parent = $target;
$target = $parent->relatedObject($object);
if (!$target) {
// Can't find related object
return $this;
}
}
$targetName = $object;
// Pop-off top object to get the parent object
// (user:photo:tag becomes user:photo - the parent table prefix)
array_pop($objects);
$parentPath = implode(':', $objects);
if (empty($parentPath)) {
// Use this table name itself for the parent object
$parentPath = $this->tableName;
}
else {
if(!isset($this->withApplied[$parentPath])) {
// If the parent object hasn't been joined yet,
// do it first (otherwise LEFT JOINs fail)
$this->with($parentPath);
}
}
// Add to with_applied to prevent duplicate joins
$this->withApplied[$targetPath] = true;
// Use the keys of the empty object to determine the columns
$select = array_keys($target->object);
foreach ($select as $i => $column) {
// Add the prefix so that load_result can determine the relationship
$select[$i] = $targetPath .'.'. $column .' AS '.
$targetPath .':'. $column;
}
// Select all of the prefixed keys in the object
$this->db->select($select);
if (in_array($target->objectName, $parent->belongsTo) ||
!isset($target->object[$parent->foreignKey($targetName)])) {
// Parent belongs_to target, use target's primary key as join column
$joinCol1 = $target->foreignKey(true, $targetPath);
$joinCol2 = $parent->foreignKey($targetName, $parentPath);
}
else {
// Parent has_one target, use parent's primary key as join column
$joinCol2 = $parent->foreignKey(true, $parentPath);
$joinCol1 = $parent->foreignKey($targetName, $targetPath);
}
// This allows for models to use different table prefixes (sharing the same database)
$joinTable =
new AetherDatabaseExpression($target->db->tablePrefix() .
$target->tableName .' AS ' .
$this->db->tablePrefix() . $targetPath);
// Join the related object into the result
$this->db->join($joinTable, $joinCol1, $joinCol2, 'LEFT');
return $this;
}
/**
* Finds and loads a single database row into the object.
*
* @param mixed $id primary key or an array of clauses
* @return AetherORM
*/
public function find($id = NULL) {
if ($id !== NULL) {
if (is_array($id)) {
// Search for all clauses
$this->db->where($id);
}
else {
// Search for a specific column
$this->db->where($this->tableName .'.'.
$this->uniqueKey($id), $id);
}
}
return $this->loadResult();
}
/**
* Finds multiple database rows and returns an iterator of the rows found.
*
* @param integer $limit SQL limit
* @param integer $offset SQL offset
* @return AetherORMIterator
*/
public function findAll($limit = NULL, $offset = NULL) {
if ($limit !== NULL && !isset($this->dbApplied['limit'])) {
// Set limit
$this->limit($limit);
}
if ($offset !== NULL && !isset($this->dbApplied['offset'])) {
// Set offset
$this->offset($offset);
}
return $this->loadResult(true);
}
/**
* Creates a key/value array from all of the objects available. Uses find_all
* to find the objects.
*
* @param string $key key column
* @param string $val value column
* @return array
*/
public function selectList($key = NULL, $val = NULL) {
if ($key === NULL)
$key = $this->primaryKey;
if ($val === NULL)
$val = $this->primaryVal;
// Return a select list from the results
return $this->select($key, $val)->findAll()->selectList($key, $val);
}
/**
* Validates the current object. This method should generally be called
* via the model, after the $_POST Validation object has been created.
*
* @param object $array Validation array
* @return boolean
*/
/*
TODO: Port validation
public function validate(Validation $array, $save = false) {
$safeArray = $array->safe_array();
if (!$array->submitted()) {
foreach ($safeArray as $key => $value) {
// Get the value from this object
$value = $this->$key;
if (is_object($value) && $value instanceof ORMIterator) {
// Convert the value to an array of primary keys
$value = $value->primaryKeyArray();
}
// Pre-fill data
$array[$key] = $value;
}
}
// Validate the array
if ($status = $array->validate()) {
// Grab only set fields (excludes missing data, unlike safe_array)
$fields = $array->as_array();
foreach ($fields as $key => $value) {
if (isset($safe_array[$key])) {
// Set new data, ignoring any missing fields or fields without rules
$this->$key = $value;
}
}
if ($save === true || is_string($save)) {
// Save this object
$this->save();
if (is_string($save)) {
// Redirect to the saved page
url::redirect($save);
}
}
}
// Return validation status
return $status;
}
*/
/**
* Saves the current object.
*
* @return AetherORM
*/
public function save() {
if (!empty($this->changed)) {
$data = array();
foreach ($this->changed as $column) {
// Compile changed data
if (($rColumn = $this->db->realColumn($column, false)) != $column)
$data[$rColumn] = $this->object[$column];
else
$data[$column] = $this->object[$column];
}
if ($this->loaded === true) {
$query = $this->db
->where($this->primaryKey, $this->object[$this->primaryKey])
->update($this->tableName, $data);
// Object has been saved
$this->saved = true;
}
else {
$query = $this->db->insert($this->tableName, $data);
// Changed to using insertId to better work with psql functions
//if ($query->count() > 0) {
if ($query->insertId() > 0) {
if (empty($this->object[$this->primaryKey])) {
// Load the insert id as the primary key
$this->object[$this->primaryKey] = $query->insertId();
}
// Object is now loaded and saved
$this->loaded = $this->saved = true;
}
}
if ($this->saved === true) {
// All changes have been saved
$this->changed = array();
}
}
if ($this->saved === true && !empty($this->changedRelations)) {
foreach ($this->changedRelations as $column => $values) {
// All values that were added
$added = array_diff($values, $this->objectRelations[$column]);
// All values that were saved
$removed = array_diff($this->objectRelations[$column], $values);
if (empty($added) && empty($removed)) {
// No need to bother
continue;
}
// Clear related columns
unset($this->related[$column]);
// Load the model
$model = AetherORM::factory(Inflector::singular($column));
if (($join_table =
array_search($column, $this->hasAndBelongsToMany)) === false)
continue;
if (is_int($joinTable)) {
// No "through" table, load the default JOIN table
$joinTable = $model->joinTable($this->tableName);
}
// Foreign keys for the join table
$objectFk = $this->foreignKey(NULL);
$relatedFk = $model->foreignKey(NULL);
if (!empty($added)) {
foreach ($added as $id) {
// Insert the new relationship
$this->db->insert($joinTable, array(
$objectFk => $this->object[$this->primaryKey],
$relatedFk => $id));
}
}
if (!empty($removed)) {
$this->db
->where($objectFk, $this->object[$this->primaryKey])
->in($relatedFk, $removed)
->delete($joinTable);
}
// Clear all relations for this column
unset($this->objectRelations[$column],
$this->changedRelations[$column]);
}
}
return $this;
}
/**
* Deletes the current object from the database. This does NOT destroy
* relationships that have been created with other objects.
*
* @return AetherORM
*/
public function delete($id = NULL) {
if ($id === NULL && $this->loaded) {
// Use the the primary key value
$id = $this->object[$this->primaryKey];
}
// Delete this object
$this->db->where($this->primaryKey, $id)->delete($this->tableName);
return $this->clear();
}
/**
* Delete all objects in the associated table. This does NOT destroy
* relationships that have been created with other objects.
*
* @param array $ids ids to delete
* @return AetherORM
*/
public function deleteAll($ids = NULL) {
if (is_array($ids)) {
// Delete only given ids
$this->db->in($this->primaryKey, $ids);
}
elseif (is_null($ids)) {
// Delete all records
$this->db->where('1=1');
}
else {
// Do nothing - safeguard
return $this;
}
// Delete all objects
$this->db->delete($this->tableName);
return $this->clear();
}
/**
* Unloads the current object and clears the status.
*
* @return AetherORM
*/
public function clear() {
// Create an array with all the columns set to NULL
$columns = array_keys($this->tableColumns);
$values = array_combine($columns, array_fill(0, count($columns), NULL));
// Replace the current object with an empty one
$this->loadValues($values);
return $this;
}
/**
* Reloads the current object from the database.
*
* @return AetherORM
*/
public function reload() {
return $this->find($this->object[$this->primaryKey]);
}
/**
* Reload column definitions.
*
* @param boolean $force force reloading
* @return AetherORM
*/
public function reloadColumns($force = false) {
if ($force === true || empty($this->tableColumns)) {
if (isset(AetherORM::$columnCache[$this->objectName])) {
// Use cached column information
$this->tableColumns = AetherORM::$columnCache[$this->objectName];
}
else {
// Load table columns
$rawFields = $this->listFields();
$fields = array();
foreach ($rawFields as $name => $row) {
// Check if there is an alias for this column
if (($alias = $this->db->aliasColumn($name, false)) != $name) {
$fields[$alias] = $row;
}
else
$fields[$name] = $row;
}
AetherORM::$columnCache[$this->objectName] = $this->tableColumns =
$fields;
}
}
return $this;
}
/**
* Tests if this object has a relationship to a different model.
*
* @param object $model related AetherORM model
* @param boolean $any check for any relations to given model
* @return boolean
*/
public function has(AetherORM $model, $any = false) {
// Determine plural or singular relation name
$related = ($model->tableNamesPlural === true) ?
$model->objectPlural : $model->objectName;
if (($joinTable = array_search($related, $this->hasAndBelongsToMany)) === false)
return false;
if (is_int($joinTable)) {
// No "through" table, load the default JOIN table
$joinTable = $model->joinTable($this->tableName);
}
if (!isset($this->objectRelations[$related])) {
// Load the object relationships
$this->changedRelations[$related] =
$this->objectRelations[$related] =
$this->loadRelations($joinTable, $model);
}
if (!$model->emptyPrimaryKey()) {
// Check if a specific object exists
return in_array($model->primaryKeyValue,
$this->changedRelations[$related]);
}
elseif ($any) {
// Check if any relations to given model exist
return !empty($this->changedRelations[$related]);
}
else {
return false;
}
}
/**
* Adds a new relationship to between this model and another.
*
* @param object $model related AetherORM model
* @return boolean
*/
public function add(AetherORM $model) {
if ($this->has($model))
return true;
// Get the faked column name
$column = $model->objectPlural;
// Add the new relation to the update
$this->changedRelations[$column][] = $model->primaryKeyValue;
if (isset($this->related[$column])) {
// Force a reload of the relationships
unset($this->related[$column]);
}
return true;
}
/**
* Adds a new relationship to between this model and another.
*
* @param object $model related AetherORM model
* @return boolean
*/
public function remove(AetherORM $model) {
if (!$this->has($model))
return false;
// Get the faked column name
$column = $model->objectPlural;
if (($key = array_search($model->primaryKeyValue,
$this->changedRelations[$column])) === false) {
return false;
}
// Remove the relationship
unset($this->changedRelations[$column][$key]);
if (isset($this->related[$column])) {
// Force a reload of the relationships
unset($this->related[$column]);
}
return true;
}
/**
* Count the number of records in the table.
*
* @return integer
*/
public function countAll() {
// Return the total number of records in a table
return $this->db->countRecords($this->tableName);
}
/**
* Proxy method to Database list_fields.
*
* @param string $table table name or NULL to use this table
* @return array
*/
public function listFields($table = NULL) {
if ($table === NULL)
$table = $this->tableName;
// Proxy to database
return $this->db->listFields($table);
}
/**
* Proxy method to Database field_data.
*
* @param string $table table name
* @return array
*/
public function fieldData($table) {
// Proxy to database
return $this->db->fieldData($table);
}
/**
* Proxy method to Database field_data.
*
* @param string $sql SQL query to clear
* @return AetherORM
*/
public function clearCache($sql = NULL) {
// Proxy to database
$this->db->clearCache($sql);
AetherORM::$columnCache = array();
return $this;
}
/**
* Returns the unique key for a specific value. This method is expected
* to be overloaded in models if the model has other unique columns.
*
* @param mixed $id unique value