ORM.php

blueskiwi -, 04/11/2009 08:34 pm

Download (33.3 kB)

 
1
<?php defined('SYSPATH') OR die('No direct access allowed.');
2
/**
3
 * [Object Relational Mapping][ref-orm] (ORM) is a method of abstracting database
4
 * access to standard PHP calls. All table rows are represented as model objects,
5
 * with object properties representing row data. ORM in Kohana generally follows
6
 * the [Active Record][ref-act] pattern.
7
 *
8
 * [ref-orm]: http://wikipedia.org/wiki/Object-relational_mapping
9
 * [ref-act]: http://wikipedia.org/wiki/Active_record
10
 *
11
 * $Id: ORM.php 3814 2008-12-18 19:17:45Z jheathco $
12
 *
13
 * @package    ORM
14
 * @author     Kohana Team
15
 * @copyright  (c) 2007-2008 Kohana Team
16
 * @license    http://kohanaphp.com/license.html
17
 */
18
class ORM_Core {
19
20
        // Current relationships
21
        protected $has_one                 = array();
22
        protected $belongs_to              = array();
23
        protected $has_many                = array();
24
        protected $has_and_belongs_to_many = array();
25
26
        // Relationships that should always be joined
27
        protected $load_with = array();
28
29
        // Current object
30
        protected $object  = array();
31
        protected $changed = array();
32
        protected $related = array();
33
        protected $loaded  = FALSE;
34
        protected $saved   = FALSE;
35
        protected $sorting;
36
37
        // Related objects
38
        protected $object_relations = array();
39
        protected $changed_relations = array();
40
41
        // Model table information
42
        protected $object_name;
43
        protected $object_plural;
44
        protected $table_name;
45
        protected $table_columns;
46
        protected $ignored_columns;
47
48
        // Table primary key and value
49
        protected $primary_key = 'id';
50
        protected $primary_val = 'name';
51
52
        // Array of foreign key name overloads
53
        protected $foreign_key = array();
54
55
        // Model configuration
56
        protected $table_names_plural = TRUE;
57
        protected $reload_on_wakeup   = TRUE;
58
59
        // Database configuration
60
        protected $db = 'default';
61
        protected $db_applied = array();
62
        
63
        // With calls already applied
64
        protected $with_applied = array();
65
66
        /**
67
         * Creates and returns a new model.
68
         *
69
         * @chainable
70
         * @param   string  model name
71
         * @param   mixed   parameter for find()
72
         * @return  ORM
73
         */
74
        public static function factory($model, $id = NULL)
75
        {
76
                // Set class name
77
                $model = ucfirst($model).'_Model';
78
79
                return new $model($id);
80
        }
81
82
        /**
83
         * Prepares the model database connection and loads the object.
84
         *
85
         * @param   mixed  parameter for find or object to load
86
         * @return  void
87
         */
88
        public function __construct($id = NULL)
89
        {
90
                // Set the object name and plural name
91
                $this->object_name   = strtolower(substr(get_class($this), 0, -6));
92
                $this->object_plural = inflector::plural($this->object_name);
93
94
                if (!isset($this->sorting))
95
                {
96
                        // Default sorting
97
                        $this->sorting = array($this->primary_key => 'asc');
98
                }
99
100
                // Initialize database
101
                $this->__initialize();
102
103
                // Clear the object
104
                $this->clear();
105
106
                if (is_object($id))
107
                {
108
                        // Load an object
109
                        $this->load_values((array) $id);
110
                }
111
                elseif (!empty($id))
112
                {                        
113
                        // Find an object
114
                        $this->find($id);
115
                }
116
        }
117
118
        /**
119
         * Prepares the model database connection, determines the table name,
120
         * and loads column information.
121
         *
122
         * @return  void
123
         */
124
        public function __initialize()
125
        {
126
                if ( ! is_object($this->db))
127
                {
128
                        // Get database instance
129
                        $this->db = Database::instance($this->db);
130
                }
131
132
                if (empty($this->table_name))
133
                {
134
                        // Table name is the same as the object name
135
                        $this->table_name = $this->object_name;
136
137
                        if ($this->table_names_plural === TRUE)
138
                        {
139
                                // Make the table name plural
140
                                $this->table_name = inflector::plural($this->table_name);
141
                        }
142
                }
143
144
                if (is_array($this->ignored_columns))
145
                {
146
                        // Make the ignored columns mirrored = mirrored
147
                        $this->ignored_columns = array_combine($this->ignored_columns, $this->ignored_columns);
148
                }
149
150
                // Load column information
151
                $this->reload_columns();
152
        }
153
154
        /**
155
         * Allows serialization of only the object data and state, to prevent
156
         * "stale" objects being unserialized, which also requires less memory.
157
         *
158
         * @return  array
159
         */
160
        public function __sleep()
161
        {
162
                // Store only information about the object
163
                return array('object_name', 'object', 'changed', 'loaded', 'saved', 'sorting');
164
        }
165
166
        /**
167
         * Prepares the database connection and reloads the object.
168
         *
169
         * @return  void
170
         */
171
        public function __wakeup()
172
        {
173
                // Initialize database
174
                $this->__initialize();
175
176
                if ($this->reload_on_wakeup === TRUE)
177
                {
178
                        // Reload the object
179
                        $this->reload();
180
                }
181
        }
182
183
        /**
184
         * Handles pass-through to database methods. Calls to query methods
185
         * (query, get, insert, update) are not allowed. Query builder methods
186
         * are chainable.
187
         *
188
         * @param   string  method name
189
         * @param   array   method arguments
190
         * @return  mixed
191
         */
192
        public function __call($method, array $args)
193
        {
194
                if (method_exists($this->db, $method))
195
                {
196
                        if (in_array($method, array('query', 'get', 'insert', 'update', 'delete')))
197
                                throw new Kohana_Exception('orm.query_methods_not_allowed');
198
199
                        // Method has been applied to the database
200
                        $this->db_applied[$method] = $method;
201
202
                        // Number of arguments passed
203
                        $num_args = count($args);
204
205
                        if ($method === 'select' AND $num_args > 3)
206
                        {
207
                                // Call select() manually to avoid call_user_func_array
208
                                $this->db->select($args);
209
                        }
210
                        else
211
                        {
212
                                // We use switch here to manually call the database methods. This is
213
                                // done for speed: call_user_func_array can take over 300% longer to
214
                                // make calls. Most database methods are 4 arguments or less, so this
215
                                // avoids almost any calls to call_user_func_array.
216
217
                                switch ($num_args)
218
                                {
219
                                        case 0:
220
                                                // Support for things like reset_select, reset_write, list_tables
221
                                                return $this->db->$method();
222
                                        break;
223
                                        case 1:
224
                                                $this->db->$method($args[0]);
225
                                        break;
226
                                        case 2:
227
                                                $this->db->$method($args[0], $args[1]);
228
                                        break;
229
                                        case 3:
230
                                                $this->db->$method($args[0], $args[1], $args[2]);
231
                                        break;
232
                                        case 4:
233
                                                $this->db->$method($args[0], $args[1], $args[2], $args[3]);
234
                                        break;
235
                                        default:
236
                                                // Here comes the snail...
237
                                                call_user_func_array(array($this->db, $method), $args);
238
                                        break;
239
                                }
240
                        }
241
242
                        return $this;
243
                }
244
                else
245
                {
246
                        throw new Kohana_Exception('core.invalid_method', $method, get_class($this));
247
                }
248
        }
249
250
        /**
251
         * Handles retrieval of all model values, relationships, and metadata.
252
         *
253
         * @param   string  column name
254
         * @return  mixed
255
         */
256
        public function __get($column)
257
        {
258
                if (isset($this->ignored_columns[$column]))
259
                {
260
                        return NULL;
261
                }
262
                elseif (array_key_exists($column, $this->object))
263
                {
264
                        return $this->object[$column];
265
                }
266
                elseif (isset($this->related[$column]))
267
                {
268
                        return $this->related[$column];
269
                }
270
                elseif ($column === 'primary_key_value')
271
                {
272
                        return $this->object[$this->primary_key];
273
                }
274
                elseif ($model = $this->related_object($column))
275
                {
276
                        // This handles the has_one and belongs_to relationships
277
278
                        if (array_key_exists($column.'_'.$model->primary_key, $this->object))
279
                        {
280
                                // Use the FK that exists in this model as the PK
281
                                $where = array($model->table_name.'.'.$model->primary_key => $this->object[$column.'_'.$model->primary_key]);
282
                        }
283
                        else
284
                        {
285
                                // Use this model PK as the FK
286
                                $where = array($this->foreign_key() => $this->object[$this->primary_key]);
287
                        }
288
289
                        // one<>alias:one relationship
290
                        return $this->related[$column] = $model->find($where);
291
                }
292
                elseif (isset($this->has_many[$column]))
293
                {
294
                        // Load the "middle" model
295
                        $through = ORM::factory(inflector::singular($this->has_many[$column]));
296
297
                        // Load the "end" model
298
                        $model = ORM::factory(inflector::singular($column));
299
300
                        // Load JOIN info
301
                        $join_table = $through->table_name;
302
                        $join_col1  = $model->foreign_key(NULL, $join_table);
303
                        $join_col2  = $model->foreign_key(TRUE);
304
305
                        // one<>alias:many relationship
306
                        return $this->related[$column] = $model
307
                                ->join($join_table, $join_col1, $join_col2)
308
                                ->where($this->foreign_key(NULL, $join_table), $this->object[$this->primary_key])
309
                                ->find_all();
310
                }
311
                elseif (in_array($column, $this->has_many))
312
                {
313
                        // one<>many relationship
314
                        return $this->related[$column] = ORM::factory(inflector::singular($column))
315
                                ->where($this->foreign_key($column), $this->object[$this->primary_key])
316
                                ->find_all();
317
                }
318
                elseif (in_array($column, $this->has_and_belongs_to_many))
319
                {
320
                        // Load the remote model, always singular
321
                        $model = ORM::factory(inflector::singular($column));
322
323
                        if ($this->has($model))
324
                        {
325
                                // many<>many relationship
326
                                return $this->related[$column] = $model
327
                                        ->in($model->primary_key, $this->changed_relations[$column])
328
                                        ->find_all();
329
                        }
330
                        else
331
                        {
332
                                // empty many<>many relationship
333
                                return $this->related[$column] = $model
334
                                        ->where($model->primary_key, NULL)
335
                                        ->find_all();
336
                        }
337
                }
338
                elseif (in_array($column, array
339
                        (
340
                                'object_name', 'object_plural', // Object
341
                                'primary_key', 'primary_val', 'table_name', 'table_columns', // Table
342
                                'loaded', 'saved', // Status
343
                                'has_one', 'belongs_to', 'has_many', 'has_and_belongs_to_many', 'load_with' // Relationships
344
                        )))
345
                {
346
                        // Model meta information
347
                        return $this->$column;
348
                }
349
                else
350
                {
351
                        throw new Kohana_Exception('core.invalid_property', $column, get_class($this));
352
                }
353
        }
354
355
        /**
356
         * Handles setting of all model values, and tracks changes between values.
357
         *
358
         * @param   string  column name
359
         * @param   mixed   column value
360
         * @return  void
361
         */
362
        public function __set($column, $value)
363
        {
364
                if (isset($this->ignored_columns[$column]))
365
                {
366
                        return NULL;
367
                }
368
                elseif (isset($this->object[$column]) OR array_key_exists($column, $this->object))
369
                {
370
                        if (isset($this->table_columns[$column]))
371
                        {
372
                                // Data has changed
373
                                $this->changed[$column] = $column;
374
375
                                // Object is no longer saved
376
                                $this->saved = FALSE;
377
                        }
378
379
                        $this->object[$column] = $this->load_type($column, $value);
380
                }
381
                elseif (in_array($column, $this->has_and_belongs_to_many) AND is_array($value))
382
                {
383
                        // Load relations
384
                        $model = ORM::factory(inflector::singular($column));
385
386
                        if ( ! isset($this->object_relations[$column]))
387
                        {
388
                                // Load relations
389
                                $this->has($model);
390
                        }
391
392
                        // Change the relationships
393
                        $this->changed_relations[$column] = $value;
394
395
                        if (isset($this->related[$column]))
396
                        {
397
                                // Force a reload of the relationships
398
                                unset($this->related[$column]);
399
                        }
400
                }
401
                else
402
                {
403
                        throw new Kohana_Exception('core.invalid_property', $column, get_class($this));
404
                }
405
        }
406
407
        /**
408
         * Checks if object data is set.
409
         *
410
         * @param   string  column name
411
         * @return  boolean
412
         */
413
        public function __isset($column)
414
        {
415
                return (isset($this->object[$column]) OR isset($this->related[$column]));
416
        }
417
418
        /**
419
         * Unsets object data.
420
         *
421
         * @param   string  column name
422
         * @return  void
423
         */
424
        public function __unset($column)
425
        {
426
                unset($this->object[$column], $this->changed[$column], $this->related[$column]);
427
        }
428
429
        /**
430
         * Displays the primary key of a model when it is converted to a string.
431
         *
432
         * @return  string
433
         */
434
        public function __toString()
435
        {
436
                return (string) $this->object[$this->primary_key];
437
        }
438
439
        /**
440
         * Returns the values of this object as an array.
441
         *
442
         * @return  array
443
         */
444
        public function as_array()
445
        {
446
                $object = array();
447
448
                foreach ($this->object as $key => $val)
449
                {
450
                        // Reconstruct the array (calls __get)
451
                        $object[$key] = $this->$key;
452
                }
453
454
                return $object;
455
        }
456
        
457
        /**
458
         * Binds another one-to-one object to this model.  One-to-one objects
459
         * can be nested using 'object1:object2' syntax
460
         *
461
         * @param string $object 
462
         * @return void
463
         */
464
        public function with($object)
465
        {
466
                if (isset($this->with_applied[$object]))
467
                {
468
                        // Don't join anything already joined
469
                        return $this;
470
                }
471
472
                $prefix = $table = $object;
473
474
                // Split object parts 
475
                $objects = explode(':', $object);
476
                $object         = $this;
477
                foreach ($objects as $object_part)
478
                {
479
                        // Go down the line of objects to find the given target
480
                        $parent = $object;
481
                        $object = $parent->related_object($object_part);
482
                        
483
                        if ( ! $object)
484
                        {
485
                                // Can't find related object
486
                                return $this;
487
                        }
488
                }
489
                
490
                $table = $object_part;
491
                
492
                if ($this->table_names_plural)
493
                {
494
                        $table = inflector::plural($table);
495
                }
496
                
497
                // Pop-off top object to get the parent object (user:photo:tag's parent is user:photo)
498
                array_pop($objects);
499
                $parent_prefix = implode(':', $objects);
500
501
                if (empty($parent_prefix))
502
                {
503
                        // Use this table name itself for the parent prefix
504
                        $parent_prefix = $this->table_name;
505
                }
506
                else
507
                {
508
                        if( ! isset($this->with_applied[$parent_prefix]))
509
                        {
510
                                // If the parent object hasn't been joined yet, do it first (otherwise LEFT JOINs fail)
511
                                $this->with($parent_prefix);
512
                        }
513
                }
514
                
515
                // Add to with_applied to prevent duplicate joins
516
                $this->with_applied[$prefix] = TRUE;
517
                
518
                // Use the keys of the empty object to determine the columns
519
                $select = array_keys($object->as_array());
520
                foreach ($select as $i => $column)
521
                {
522
                        // Add the prefix so that load_result can determine the relationship
523
                        $select[$i] = $table.'.'.$column.' AS '.$table.':'.$column;
524
                }
525
526
                // Select all of the prefixed keys in the object
527
                $this->db->select($select);
528
529
                // Use last object part to generate foreign key
530
                $foreign_key = $object_part.'_'.$object->primary_key;
531
532
                if (array_key_exists($foreign_key, $parent->object))
533
                {        
534
                        // Foreign key exists in the joined object's parent
535
                        $join_col1 = $object->foreign_key(TRUE, $table);
536
                        $join_col2 = $parent_prefix.'.'.$foreign_key;
537
                }
538
                else
539
                {
540
                        $join_col1 = $parent->foreign_key(NULL, $table);
541
                        $join_col2 = $parent_prefix.'.'.$parent->primary_key;
542
                }
543
544
                // Join the related object into the result
545
                $this->db->join($object->table_name, $join_col1, $join_col2, 'LEFT');
546
547
                return $this;
548
        }
549
550
        /**
551
         * Finds and loads a single database row into the object.
552
         *
553
         * @chainable
554
         * @param   mixed  primary key or an array of clauses
555
         * @return  ORM
556
         */
557
        public function find($id = NULL)
558
        {
559
                if ($id !== NULL)
560
                {
561
                        if (is_array($id))
562
                        {
563
                                // Search for all clauses
564
                                $this->db->where($id);
565
                        }
566
                        else
567
                        {
568
                                // Search for a specific column
569
                                $this->db->where($this->table_name.'.'.$this->unique_key($id), $id);
570
                        }
571
                }
572
573
                return $this->load_result();
574
        }
575
576
        /**
577
         * Finds multiple database rows and returns an iterator of the rows found.
578
         *
579
         * @chainable
580
         * @param   integer  SQL limit
581
         * @param   integer  SQL offset
582
         * @return  ORM_Iterator
583
         */
584
        public function find_all($limit = NULL, $offset = NULL)
585
        {
586
                if ($limit !== NULL AND ! isset($this->db_applied['limit']))
587
                {
588
                        // Set limit
589
                        $this->limit($limit);
590
                }
591
592
                if ($offset !== NULL AND ! isset($this->db_applied['offset']))
593
                {
594
                        // Set offset
595
                        $this->offset($offset);
596
                }
597
598
                return $this->load_result(TRUE);
599
        }
600
601
        /**
602
         * Creates a key/value array from all of the objects available. Uses find_all
603
         * to find the objects.
604
         *
605
         * @param   string  key column
606
         * @param   string  value column
607
         * @return  array
608
         */
609
        public function select_list($key = NULL, $val = NULL)
610
        {
611
                if ($key === NULL)
612
                {
613
                        $key = $this->primary_key;
614
                }
615
616
                if ($val === NULL)
617
                {
618
                        $val = $this->primary_val;
619
                }
620
621
                // Return a select list from the results
622
                return $this->select($key, $val)->find_all()->select_list($key, $val);
623
        }
624
625
        /**
626
         * Validates the current object. This method should generally be called
627
         * via the model, after the $_POST Validation object has been created.
628
         *
629
         * @param   object   Validation array
630
         * @return  boolean
631
         */
632
        public function validate(Validation $array, $save = FALSE)
633
        {
634
                if ( ! $array->submitted())
635
                {
636
                        $safe_array = $array->safe_array();
637
638
                        foreach ($safe_array as $key => $value)
639
                        {
640
                                // Get the value from this object
641
                                $value = $this->$key;
642
643
                                if (is_object($value) AND $value instanceof ORM_Iterator)
644
                                {
645
                                        // Convert the value to an array of primary keys
646
                                        $value = $value->primary_key_array();
647
                                }
648
649
                                // Pre-fill data
650
                                $array[$key] = $value;
651
                        }
652
                }
653
654
                // Validate the array
655
                if ($status = $array->validate())
656
                {
657
                        $safe_array = $array->safe_array();
658
659
                        foreach ($safe_array as $key => $value)
660
                        {
661
                                // Set new data
662
                                $this->$key = $value;
663
                        }
664
665
                        if ($save === TRUE OR is_string($save))
666
                        {
667
                                // Save this object
668
                                $this->save();
669
670
                                if (is_string($save))
671
                                {
672
                                        // Redirect to the saved page
673
                                        url::redirect($save);
674
                                }
675
                        }
676
                }
677
678
                // Return validation status
679
                return $status;
680
        }
681
682
        /**
683
         * Saves the current object.
684
         *
685
         * @chainable
686
         * @return  ORM
687
         */
688
        public function save()
689
        {
690
                if ( ! empty($this->changed))
691
                {
692
                        $data = array();
693
                        foreach ($this->changed as $column)
694
                        {
695
                                // Compile changed data
696
                                $data[$column] = $this->object[$column];
697
                        }
698
699
                        if ($this->loaded === TRUE)
700
                        {
701
                                $query = $this->db
702
                                        ->where($this->primary_key, $this->object[$this->primary_key])
703
                                        ->update($this->table_name, $data);
704
705
                                // Object has been saved
706
                                $this->saved = TRUE;
707
                        }
708
                        else
709
                        {
710
                                $query = $this->db
711
                                        ->insert($this->table_name, $data);
712
713
                                if ($query->count() > 0)
714
                                {
715
                                        if (empty($this->object[$this->primary_key]))
716
                                        {
717
                                                // Load the insert id as the primary key
718
                                                $this->object[$this->primary_key] = $query->insert_id();
719
                                        }
720
721
                                        // Object is now loaded and saved
722
                                        $this->loaded = $this->saved = TRUE;
723
                                }
724
                        }
725
726
                        if ($this->saved === TRUE)
727
                        {
728
                                // All changes have been saved
729
                                $this->changed = array();
730
                        }
731
                }
732
733
                if ($this->saved === TRUE AND ! empty($this->changed_relations))
734
                {
735
                        foreach ($this->changed_relations as $column => $values)
736
                        {
737
                                // All values that were added
738
                                $added = array_diff($values, $this->object_relations[$column]);
739
740
                                // All values that were saved
741
                                $removed = array_diff($this->object_relations[$column], $values);
742
743
                                if (empty($added) AND empty($removed))
744
                                {
745
                                        // No need to bother
746
                                        continue;
747
                                }
748
749
                                // Clear related columns
750
                                unset($this->related[$column]);
751
752
                                // Load the model
753
                                $model = ORM::factory(inflector::singular($column));
754
755
                                if (($join_table = array_search($column, $this->has_and_belongs_to_many)) === FALSE)
756
                                        continue;
757
758
                                if (is_int($join_table))
759
                                {
760
                                        // No "through" table, load the default JOIN table
761
                                        $join_table = $model->join_table($this->table_name);
762
                                }
763
764
                                // Foreign keys for the join table
765
                                $object_fk  = $this->foreign_key(NULL);
766
                                $related_fk = $model->foreign_key(NULL);
767
768
                                if ( ! empty($added))
769
                                {
770
                                        foreach ($added as $id)
771
                                        {
772
                                                // Insert the new relationship
773
                                                $this->db->insert($join_table, array
774
                                                (
775
                                                        $object_fk  => $this->object[$this->primary_key],
776
                                                        $related_fk => $id,
777
                                                ));
778
                                        }
779
                                }
780
781
                                if ( ! empty($removed))
782
                                {
783
                                        $this->db
784
                                                ->where($object_fk, $this->object[$this->primary_key])
785
                                                ->in($related_fk, $removed)
786
                                                ->delete($join_table);
787
                                }
788
789
                                // Clear all relations for this column
790
                                unset($this->object_relations[$column], $this->changed_relations[$column]);
791
                        }
792
                }
793
794
                return $this;
795
        }
796
797
        /**
798
         * Deletes the current object from the database. This does NOT destroy
799
         * relationships that have been created with other objects.
800
         *
801
         * @chainable
802
         * @return  ORM
803
         */
804
        public function delete($id = NULL)
805
        {
806
                if ($id === NULL AND $this->loaded)
807
                {
808
                        // Use the the primary key value
809
                        $id = $this->object[$this->primary_key];
810
                }
811
812
                // Delete this object
813
                $this->db->where($this->primary_key, $id)->delete($this->table_name);
814
815
                return $this->clear();
816
        }
817
818
        /**
819
         * Delete all objects in the associated table. This does NOT destroy
820
         * relationships that have been created with other objects.
821
         *
822
         * @chainable
823
         * @param   array  ids to delete
824
         * @return  ORM
825
         */
826
        public function delete_all($ids = NULL)
827
        {
828
                if (is_array($ids))
829
                {
830
                        // Delete only given ids
831
                        $this->db->in($this->primary_key, $ids);
832
                }
833
                elseif (is_null($ids))
834
                {
835
                        // Delete all records
836
                        $this->db->where(TRUE);
837
                }
838
                else
839
                {
840
                        // Do nothing - safeguard
841
                        return $this;
842
                }
843
844
                // Delete all objects
845
                $this->db->delete($this->table_name);
846
847
                return $this->clear();
848
        }
849
850
        /**
851
         * Unloads the current object and clears the status.
852
         *
853
         * @chainable
854
         * @return  ORM
855
         */
856
        public function clear()
857
        {
858
                // Create an array with all the columns set to NULL
859
                $columns = array_keys($this->table_columns);
860
                $values  = array_combine($columns, array_fill(0, count($columns), NULL));
861
862
                // Replace the current object with an empty one
863
                $this->load_values($values);
864
865
                return $this;
866
        }
867
868
        /**
869
         * Reloads the current object from the database.
870
         *
871
         * @chainable
872
         * @return  ORM
873
         */
874
        public function reload()
875
        {
876
                return $this->find($this->object[$this->primary_key]);
877
        }
878
879
        /**
880
         * Reload column definitions.
881
         *
882
         * @chainable
883
         * @param   boolean  force reloading
884
         * @return  ORM
885
         */
886
        public function reload_columns($force = FALSE)
887
        {
888
                if ($force === TRUE OR empty($this->table_columns))
889
                {
890
                        // Load table columns
891
                        $this->table_columns = $this->db->list_fields($this->table_name, TRUE);
892
                }
893
894
                return $this;
895
        }
896
897
        /**
898
         * Tests if this object has a relationship to a different model.
899
         *
900
         * @param   object   related ORM model
901
         * @return  boolean
902
         */
903
        public function has(ORM $model)
904
        {
905
                // Get the plural object name as the related name
906
                $related = $model->object_plural;
907
908
                if (($join_table = array_search($related, $this->has_and_belongs_to_many)) === FALSE)
909
                        return FALSE;
910
911
                if (is_int($join_table))
912
                {
913
                        // No "through" table, load the default JOIN table
914
                        $join_table = $model->join_table($this->table_name);
915
                }
916
917
                if ( ! isset($this->object_relations[$related]))
918
                {
919
                        // Load the object relationships
920
                        $this->changed_relations[$related] = $this->object_relations[$related] = $this->load_relations($join_table, $model);
921
                }
922
923
                if ($model->loaded)
924
                {
925
                        // Check if a specific object exists
926
                        return in_array($model->primary_key_value, $this->changed_relations[$related]);
927
                }
928
                else
929
                {
930
                        return ! empty($this->changed_relations[$related]);
931
                }
932
        }
933
934
        /**
935
         * Adds a new relationship to between this model and another.
936
         *
937
         * @param   object   related ORM model
938
         * @return  boolean
939
         */
940
        public function add(ORM $model)
941
        {
942
                if ($this->has($model))
943
                        return TRUE;
944
945
                // Get the faked column name
946
                $column = $model->object_plural;
947
948
                // Add the new relation to the update
949
                $this->changed_relations[$column][] = $model->primary_key_value;
950
951
                if (isset($this->related[$column]))
952
                {
953
                        // Force a reload of the relationships
954
                        unset($this->related[$column]);
955
                }
956
957
                return TRUE;
958
        }
959
960
        /**
961
         * Adds a new relationship to between this model and another.
962
         *
963
         * @param   object   related ORM model
964
         * @return  boolean
965
         */
966
        public function remove(ORM $model)
967
        {
968
                if ( ! $this->has($model))
969
                        return FALSE;
970
971
                // Get the faked column name
972
                $column = $model->object_plural;
973
974
                if ($model->loaded)
975
                {
976
                        if (($key = array_search($model->primary_key_value, $this->changed_relations[$column])) === FALSE)
977
                                return FALSE;
978
979
                        // Remove the relationship
980
                        unset($this->changed_relations[$column][$key]);
981
                }
982
                else
983
                {
984
                        // Clear all of this objects relationships
985
                        $this->changed_relations[$column] = array();
986
                }
987
988
                if (isset($this->related[$column]))
989
                {
990
                        // Force a reload of the relationships
991
                        unset($this->related[$column]);
992
                }
993
994
                return TRUE;
995
        }
996
997
        /**
998
         * Count the number of records in the table.
999
         *
1000
         * @return  integer
1001
         */
1002
        public function count_all()
1003
        {
1004
                // Return the total number of records in a table
1005
                return $this->db->count_records($this->table_name);
1006
        }
1007
1008
        /**
1009
         * Count the number of records in the last query, without LIMIT or OFFSET applied.
1010
         *
1011
         * @return  integer
1012
         */
1013
        public function count_last_query()
1014
        {
1015
                if ($sql = $this->db->last_query())
1016
                {
1017
                        if (stripos($sql, 'LIMIT') !== FALSE)
1018
                        {
1019
                                // Remove LIMIT from the SQL
1020
                                $sql = preg_replace('/\sLIMIT\s+[^a-z]+/i', ' ', $sql);
1021
                        }
1022
1023
                        if (stripos($sql, 'OFFSET') !== FALSE)
1024
                        {
1025
                                // Remove OFFSET from the SQL
1026
                                $sql = preg_replace('/\sOFFSET\s+\d+/i', '', $sql);
1027
                        }
1028
1029
                        // Get the total rows from the last query executed
1030
                        $result = $this->db->query
1031
                        (
1032
                                'SELECT COUNT(*) AS '.$this->db->escape_column('total_rows').' '.
1033
                                'FROM ('.trim($sql).') AS '.$this->db->escape_table('counted_results')
1034
                        );
1035
1036
                        // Return the total number of rows from the query
1037
                        return (int) $result->current()->total_rows;
1038
                }
1039
1040
                return FALSE;
1041
        }
1042
1043
        /**
1044
         * Proxy method to Database list_fields.
1045
         *
1046
         * @param   string  table name
1047
         * @return  array
1048
         */
1049
        public function list_fields($table)
1050
        {
1051
                // Proxy to database
1052
                return $this->db->list_fields($table);
1053
        }
1054
1055
        /**
1056
         * Proxy method to Database field_data.
1057
         *
1058
         * @param   string  table name
1059
         * @return  array
1060
         */
1061
        public function field_data($table)
1062
        {
1063
                // Proxy to database
1064
                return $this->db->field_data($table);
1065
        }
1066
1067
        /**
1068
         * Proxy method to Database last_query.
1069
         *
1070
         * @return  string
1071
         */
1072
        public function last_query()
1073
        {
1074
                // Proxy to database
1075
                return $this->db->last_query();
1076
        }
1077
1078
        /**
1079
         * Proxy method to Database field_data.
1080
         *
1081
         * @chainable
1082
         * @param   string  SQL query to clear
1083
         * @return  ORM
1084
         */
1085
        public function clear_cache($sql = NULL)
1086
        {
1087
                // Proxy to database
1088
                $this->db->clear_cache($sql);
1089
1090
                return $this;
1091
        }
1092
1093
        /**
1094
         * Returns the unique key for a specific value. This method is expected
1095
         * to be overloaded in models if the model has other unique columns.
1096
         *
1097
         * @param   mixed   unique value
1098
         * @return  string
1099
         */
1100
        public function unique_key($id)
1101
        {
1102
                return $this->primary_key;
1103
        }
1104
1105
        /**
1106
         * Determines the name of a foreign key for a specific table.
1107
         *
1108
         * @param   string  related table name
1109
         * @param   string  prefix table name (used for JOINs)
1110
         * @return  string
1111
         */
1112
        public function foreign_key($table = NULL, $prefix_table = NULL)
1113
        {
1114
                if ($table === TRUE)
1115
                {
1116
                        if (is_string($prefix_table))
1117
                        {
1118
                                // Use prefix table name and this table's PK
1119
                                return $prefix_table.'.'.$this->primary_key;
1120
                        }
1121
                        else
1122
                        {
1123
                                // Return the name of this table's PK
1124
                                return $this->table_name.'.'.$this->primary_key;
1125
                        }
1126
                }
1127
1128
                if (is_string($prefix_table))
1129
                {
1130
                        // Add a period for prefix_table.column support
1131
                        $prefix_table .= '.';
1132
                }
1133
1134
                if (isset($this->foreign_key[$table]))
1135
                {
1136
                        // Use the defined foreign key name, no magic here!
1137
                        $foreign_key = $this->foreign_key[$table];
1138
                }
1139
                else
1140
                {
1141
                        if ( ! is_string($table) OR ! isset($this->object[$table.'_'.$this->primary_key]))
1142
                        {
1143
                                // Use this table
1144
                                $table = $this->table_name;
1145
1146
                                if (strpos($table, '.') !== FALSE)
1147
                                {
1148
                                        // Hack around support for PostgreSQL schemas
1149
                                        list ($schema, $table) = explode('.', $table, 2);
1150
                                }
1151
1152
                                if ($this->table_names_plural === TRUE)
1153
                                {
1154
                                        // Make the key name singular
1155
                                        $table = inflector::singular($table);
1156
                                }
1157
                        }
1158
1159
                        $foreign_key = $table.'_'.$this->primary_key;
1160
                }
1161
1162
                return $prefix_table.$foreign_key;
1163
        }
1164
1165
        /**
1166
         * This uses alphabetical comparison to choose the name of the table.
1167
         *
1168
         * Example: The joining table of users and roles would be roles_users,
1169
         * because "r" comes before "u". Joining products and categories would
1170
         * result in categories_products, because "c" comes before "p".
1171
         *
1172
         * Example: zoo > zebra > robber > ocean > angel > aardvark
1173
         *
1174
         * @param   string  table name
1175
         * @return  string
1176
         */
1177
        public function join_table($table)
1178
        {
1179
                if ($this->table_name > $table)
1180
                {
1181
                        $table = $table.'_'.$this->table_name;
1182
                }
1183
                else
1184
                {
1185
                        $table = $this->table_name.'_'.$table;
1186
                }
1187
1188
                return $table;
1189
        }
1190
1191
        /**
1192
         * Returns an ORM model for the given object name;
1193
         *
1194
         * @param   string  object name
1195
         * @return  ORM
1196
         */
1197
        protected function related_object($object)
1198
        {
1199
                if (isset($this->has_one[$object]))
1200
                {
1201
                        $object = ORM::factory($this->has_one[$object]);
1202
                }
1203
                elseif (isset($this->belongs_to[$object]))
1204
                {
1205
                        $object = ORM::factory($this->belongs_to[$object]);
1206
                }
1207
                elseif (in_array($object, $this->has_one) OR in_array($object, $this->belongs_to))
1208
                {
1209
                        $object = ORM::factory($object);
1210
                }
1211
                else
1212
                {
1213
                        return FALSE;
1214
                }
1215
1216
                return $object;
1217
        }
1218
1219
        /**
1220
         * Loads an array of values into into the current object.
1221
         *
1222
         * @chainable
1223
         * @param   array  values to load
1224
         * @return  ORM
1225
         */
1226
        public function load_values(array $values)
1227
        {
1228
                if (array_key_exists($this->primary_key, $values))
1229
                {
1230
                        // Replace the object and reset the object status
1231
                        $this->object = $this->changed = $this->related = array();
1232
1233
                        // Set the loaded and saved object status based on the primary key
1234
                        $this->loaded = $this->saved = (bool) $values[$this->primary_key];
1235
                }
1236
1237
                // Related objects
1238
                $related = array();
1239
1240
                foreach ($values as $column => $value)
1241
                {
1242
                        if (strpos($column, ':') === FALSE)
1243
                        {
1244
                                if (isset($this->table_columns[$column]))
1245
                                {
1246
                                        // The type of the value can be determined, convert the value
1247
                                        $value = $this->load_type($column, $value);
1248
                                }
1249
1250
                                $this->object[$column] = $value;
1251
                        }
1252
                        else
1253
                        {
1254
                                list ($prefix, $column) = explode(':', $column, 2);
1255
1256
                                $related[$prefix][$column] = $value;
1257
                        }
1258
                }
1259
1260
                if ( ! empty($related))
1261
                {
1262
                        foreach ($related as $object => $values)
1263
                        {
1264
                                // Load the related objects with the values in the result
1265
                                if ($this->table_names_plural) {
1266
                                        $object = inflector::singular($object);
1267
                                }
1268
                                $this->related[$object] = $this->related_object($object)->load_values($values);
1269
                        }
1270
                }
1271
                
1272
                return $this;
1273
        }
1274
1275
        /**
1276
         * Loads a value according to the types defined by the column metadata.
1277
         *
1278
         * @param   string  column name
1279
         * @param   mixed   value to load
1280
         * @return  mixed
1281
         */
1282
        protected function load_type($column, $value)
1283
        {
1284
                if (is_object($value) OR is_array($value) OR ! isset($this->table_columns[$column]))
1285
                        return $value;
1286
1287
                // Load column data
1288
                $column = $this->table_columns[$column];
1289
1290
                if ($value === NULL AND ! empty($column['null']))
1291
                        return $value;
1292
1293
                if ( ! empty($column['binary']) AND ! empty($column['exact']) AND (int) $column['length'] === 1)
1294
                {
1295
                        // Use boolean for BINARY(1) fields
1296
                        $column['type'] = 'boolean';
1297
                }
1298
1299
                switch ($column['type'])
1300
                {
1301
                        case 'int':
1302
                                if ($value === '' AND ! empty($column['null']))
1303
                                {
1304
                                        // Forms will only submit strings, so empty integer values must be null
1305
                                        $value = NULL;
1306
                                }
1307
                                elseif ((float) $value > PHP_INT_MAX)
1308
                                {
1309
                                        // This number cannot be represented by a PHP integer, so we convert it to a string
1310
                                        $value = (string) $value;
1311
                                }
1312
                                else
1313
                                {
1314
                                        $value = (int) $value;
1315
                                }
1316
                        break;
1317
                        case 'float':
1318
                                $value = (float) $value;
1319
                        break;
1320
                        case 'boolean':
1321
                                $value = (bool) $value;
1322
                        break;
1323
                        case 'string':
1324
                                $value = (string) $value;
1325
                        break;
1326
                }
1327
1328
                return $value;
1329
        }
1330
1331
        /**
1332
         * Loads a database result, either as a new object for this model, or as
1333
         * an iterator for multiple rows.
1334
         *
1335
         * @chainable
1336
         * @param   boolean       return an iterator or load a single row
1337
         * @return  ORM           for single rows
1338
         * @return  ORM_Iterator  for multiple rows
1339
         */
1340
        protected function load_result($array = FALSE)
1341
        {
1342
                if ($array === FALSE)
1343
                {
1344
                        // Only fetch 1 record
1345
                        $this->db->limit(1);
1346
                }
1347
1348
                if ( ! isset($this->db_applied['select']))
1349
                {
1350
                        // Select all columns by default
1351
                        $this->db->select($this->table_name.'.*');
1352
                }
1353
                
1354
                if ( ! empty($this->load_with))
1355
                {
1356
                        foreach ($this->load_with as $object)
1357
                        {
1358
                                // Join each object into the results
1359
                                $this->with($object);
1360
                        }
1361
                }
1362
1363
                if ( ! isset($this->db_applied['orderby']) AND ! empty($this->sorting))
1364
                {
1365
                        $sorting = array();
1366
                        foreach ($this->sorting as $column => $direction)
1367
                        {
1368
                                if (strpos($column, '.') === FALSE)
1369
                                {
1370
                                        // Keeps sorting working properly when using JOINs on
1371
                                        // tables with columns of the same name
1372
                                        $column = $this->table_name.'.'.$column;
1373
                                }
1374
1375
                                $sorting[$column] = $direction;
1376
                        }
1377
1378
                        // Apply the user-defined sorting
1379
                        $this->db->orderby($sorting);
1380
                }
1381
1382
                // Load the result
1383
                $result = $this->db->get($this->table_name);
1384
1385
                if ($array === TRUE)
1386
                {
1387
                        // Return an iterated result
1388
                        return new ORM_Iterator($this, $result);
1389
                }
1390
1391
                if ($result->count() === 1)
1392
                {
1393
                        // Load object values
1394
                        $this->load_values($result->result(FALSE)->current());
1395
                }
1396
                else
1397
                {
1398
                        // Clear the object, nothing was found
1399
                        $this->clear();
1400
                }
1401
1402
                return $this;
1403
        }
1404
1405
        /**
1406
         * Return an array of all the primary keys of the related table.
1407
         *
1408
         * @param   string  table name
1409
         * @param   object  ORM model to find relations of
1410
         * @return  array
1411
         */
1412
        protected function load_relations($table, ORM $model)
1413
        {
1414
                $query = $this->db
1415
                        ->select($model->foreign_key(NULL).' AS id')
1416
                        ->from($table)
1417
                        ->where($this->foreign_key(NULL, $table), $this->object[$this->primary_key])
1418
                        ->get()
1419
                        ->result(TRUE);
1420
1421
                $relations = array();
1422
                foreach ($query as $row)
1423
                {
1424
                        $relations[] = $row->id;
1425
                }
1426
1427
                return $relations;
1428
        }
1429
1430
} // End ORM