/
Table.php
2686 lines (2454 loc) · 89.7 KB
/
Table.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
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\ORM;
use ArrayObject;
use BadMethodCallException;
use Cake\Core\App;
use Cake\Database\Schema\TableSchema;
use Cake\Database\Type;
use Cake\Datasource\ConnectionInterface;
use Cake\Datasource\EntityInterface;
use Cake\Datasource\Exception\InvalidPrimaryKeyException;
use Cake\Datasource\RepositoryInterface;
use Cake\Datasource\RulesAwareTrait;
use Cake\Event\EventDispatcherInterface;
use Cake\Event\EventDispatcherTrait;
use Cake\Event\EventListenerInterface;
use Cake\Event\EventManager;
use Cake\ORM\Association\BelongsTo;
use Cake\ORM\Association\BelongsToMany;
use Cake\ORM\Association\HasMany;
use Cake\ORM\Association\HasOne;
use Cake\ORM\Exception\MissingEntityException;
use Cake\ORM\Exception\RolledbackTransactionException;
use Cake\ORM\Rule\IsUnique;
use Cake\Utility\Inflector;
use Cake\Validation\ValidatorAwareTrait;
use InvalidArgumentException;
use RuntimeException;
/**
* Represents a single database table.
*
* Exposes methods for retrieving data out of it, and manages the associations
* this table has to other tables. Multiple instances of this class can be created
* for the same database table with different aliases, this allows you to address
* your database structure in a richer and more expressive way.
*
* ### Retrieving data
*
* The primary way to retrieve data is using Table::find(). See that method
* for more information.
*
* ### Dynamic finders
*
* In addition to the standard find($type) finder methods, CakePHP provides dynamic
* finder methods. These methods allow you to easily set basic conditions up. For example
* to filter users by username you would call
*
* ```
* $query = $users->findByUsername('mark');
* ```
*
* You can also combine conditions on multiple fields using either `Or` or `And`:
*
* ```
* $query = $users->findByUsernameOrEmail('mark', 'mark@example.org');
* ```
*
* ### Bulk updates/deletes
*
* You can use Table::updateAll() and Table::deleteAll() to do bulk updates/deletes.
* You should be aware that events will *not* be fired for bulk updates/deletes.
*
* ### Callbacks/events
*
* Table objects provide a few callbacks/events you can hook into to augment/replace
* find operations. Each event uses the standard event subsystem in CakePHP
*
* - `beforeFind(Event $event, Query $query, ArrayObject $options, boolean $primary)`
* Fired before each find operation. By stopping the event and supplying a
* return value you can bypass the find operation entirely. Any changes done
* to the $query instance will be retained for the rest of the find. The
* $primary parameter indicates whether or not this is the root query,
* or an associated query.
*
* - `buildValidator(Event $event, Validator $validator, string $name)`
* Allows listeners to modify validation rules for the provided named validator.
*
* - `buildRules(Event $event, RulesChecker $rules)`
* Allows listeners to modify the rules checker by adding more rules.
*
* - `beforeRules(Event $event, EntityInterface $entity, ArrayObject $options, string $operation)`
* Fired before an entity is validated using the rules checker. By stopping this event,
* you can return the final value of the rules checking operation.
*
* - `afterRules(Event $event, EntityInterface $entity, ArrayObject $options, bool $result, string $operation)`
* Fired after the rules have been checked on the entity. By stopping this event,
* you can return the final value of the rules checking operation.
*
* - `beforeSave(Event $event, EntityInterface $entity, ArrayObject $options)`
* Fired before each entity is saved. Stopping this event will abort the save
* operation. When the event is stopped the result of the event will be returned.
*
* - `afterSave(Event $event, EntityInterface $entity, ArrayObject $options)`
* Fired after an entity is saved.
*
* - `afterSaveCommit(Event $event, EntityInterface $entity, ArrayObject $options)`
* Fired after the transaction in which the save operation is wrapped has been committed.
* It’s also triggered for non atomic saves where database operations are implicitly committed.
* The event is triggered only for the primary table on which save() is directly called.
* The event is not triggered if a transaction is started before calling save.
*
* - `beforeDelete(Event $event, EntityInterface $entity, ArrayObject $options)`
* Fired before an entity is deleted. By stopping this event you will abort
* the delete operation.
*
* - `afterDelete(Event $event, EntityInterface $entity, ArrayObject $options)`
* Fired after an entity has been deleted.
*
* @see \Cake\Event\EventManager for reference on the events system.
*/
class Table implements RepositoryInterface, EventListenerInterface, EventDispatcherInterface
{
use EventDispatcherTrait;
use RulesAwareTrait;
use ValidatorAwareTrait;
/**
* Name of default validation set.
*
* @var string
*/
const DEFAULT_VALIDATOR = 'default';
/**
* The alias this object is assigned to validators as.
*
* @var string
*/
const VALIDATOR_PROVIDER_NAME = 'table';
/**
* The rules class name that is used.
*
* @var string
*/
const RULES_CLASS = 'Cake\ORM\RulesChecker';
/**
* Name of the table as it can be found in the database
*
* @var string
*/
protected $_table;
/**
* Human name giving to this particular instance. Multiple objects representing
* the same database table can exist by using different aliases.
*
* @var string
*/
protected $_alias;
/**
* Connection instance
*
* @var \Cake\Datasource\ConnectionInterface
*/
protected $_connection;
/**
* The schema object containing a description of this table fields
*
* @var \Cake\Database\Schema\TableSchema
*/
protected $_schema;
/**
* The name of the field that represents the primary key in the table
*
* @var string|array
*/
protected $_primaryKey;
/**
* The name of the field that represents a human readable representation of a row
*
* @var string
*/
protected $_displayField;
/**
* The associations container for this Table.
*
* @var \Cake\ORM\AssociationCollection
*/
protected $_associations;
/**
* BehaviorRegistry for this table
*
* @var \Cake\ORM\BehaviorRegistry
*/
protected $_behaviors;
/**
* The name of the class that represent a single row for this table
*
* @var string
*/
protected $_entityClass;
/**
* Registry key used to create this table object
*
* @var string
*/
protected $_registryAlias;
/**
* Initializes a new instance
*
* The $config array understands the following keys:
*
* - table: Name of the database table to represent
* - alias: Alias to be assigned to this table (default to table name)
* - connection: The connection instance to use
* - entityClass: The fully namespaced class name of the entity class that will
* represent rows in this table.
* - schema: A \Cake\Database\Schema\TableSchema object or an array that can be
* passed to it.
* - eventManager: An instance of an event manager to use for internal events
* - behaviors: A BehaviorRegistry. Generally not used outside of tests.
* - associations: An AssociationCollection instance.
* - validator: A Validator instance which is assigned as the "default"
* validation set, or an associative array, where key is the name of the
* validation set and value the Validator instance.
*
* @param array $config List of options for this table
*/
public function __construct(array $config = [])
{
if (!empty($config['registryAlias'])) {
$this->setRegistryAlias($config['registryAlias']);
}
if (!empty($config['table'])) {
$this->setTable($config['table']);
}
if (!empty($config['alias'])) {
$this->setAlias($config['alias']);
}
if (!empty($config['connection'])) {
$this->setConnection($config['connection']);
}
if (!empty($config['schema'])) {
$this->setSchema($config['schema']);
}
if (!empty($config['entityClass'])) {
$this->setEntityClass($config['entityClass']);
}
$eventManager = $behaviors = $associations = null;
if (!empty($config['eventManager'])) {
$eventManager = $config['eventManager'];
}
if (!empty($config['behaviors'])) {
$behaviors = $config['behaviors'];
}
if (!empty($config['associations'])) {
$associations = $config['associations'];
}
if (!empty($config['validator'])) {
if (!is_array($config['validator'])) {
$this->validator(static::DEFAULT_VALIDATOR, $config['validator']);
} else {
foreach ($config['validator'] as $name => $validator) {
$this->validator($name, $validator);
}
}
}
$this->_eventManager = $eventManager ?: new EventManager();
$this->_behaviors = $behaviors ?: new BehaviorRegistry();
$this->_behaviors->setTable($this);
$this->_associations = $associations ?: new AssociationCollection();
$this->initialize($config);
$this->_eventManager->on($this);
$this->dispatchEvent('Model.initialize');
}
/**
* Get the default connection name.
*
* This method is used to get the fallback connection name if an
* instance is created through the TableRegistry without a connection.
*
* @return string
* @see \Cake\ORM\TableRegistry::get()
*/
public static function defaultConnectionName()
{
return 'default';
}
/**
* Initialize a table instance. Called after the constructor.
*
* You can use this method to define associations, attach behaviors
* define validation and do any other initialization logic you need.
*
* ```
* public function initialize(array $config)
* {
* $this->belongsTo('Users');
* $this->belongsToMany('Tagging.Tags');
* $this->setPrimaryKey('something_else');
* }
* ```
*
* @param array $config Configuration options passed to the constructor
* @return void
*/
public function initialize(array $config)
{
}
/**
* Sets the database table name.
*
* @param string $table Table name.
* @return $this
*/
public function setTable($table)
{
$this->_table = $table;
return $this;
}
/**
* Returns the database table name.
*
* @return string
*/
public function getTable()
{
if ($this->_table === null) {
$table = namespaceSplit(get_class($this));
$table = substr(end($table), 0, -5);
if (!$table) {
$table = $this->getAlias();
}
$this->_table = Inflector::underscore($table);
}
return $this->_table;
}
/**
* Returns the database table name or sets a new one.
*
* @deprecated 3.4.0 Use setTable()/getTable() instead.
* @param string|null $table the new table name
* @return string
*/
public function table($table = null)
{
if ($table !== null) {
$this->setTable($table);
}
return $this->getTable();
}
/**
* Sets the table alias.
*
* @param string $alias Table alias
* @return $this
*/
public function setAlias($alias)
{
$this->_alias = $alias;
return $this;
}
/**
* Returns the table alias.
*
* @return string
*/
public function getAlias()
{
if ($this->_alias === null) {
$alias = namespaceSplit(get_class($this));
$alias = substr(end($alias), 0, -5) ?: $this->_table;
$this->_alias = $alias;
}
return $this->_alias;
}
/**
* {@inheritDoc}
* @deprecated 3.4.0 Use setAlias()/getAlias() instead.
*/
public function alias($alias = null)
{
if ($alias !== null) {
$this->setAlias($alias);
}
return $this->getAlias();
}
/**
* Alias a field with the table's current alias.
*
* If field is already aliased it will result in no-op.
*
* @param string $field The field to alias.
* @return string The field prefixed with the table alias.
*/
public function aliasField($field)
{
if (strpos($field, '.') !== false) {
return $field;
}
return $this->getAlias() . '.' . $field;
}
/**
* Sets the table registry key used to create this table instance.
*
* @param string $registryAlias The key used to access this object.
* @return $this
*/
public function setRegistryAlias($registryAlias)
{
$this->_registryAlias = $registryAlias;
return $this;
}
/**
* Returns the table registry key used to create this table instance.
*
* @return string
*/
public function getRegistryAlias()
{
if ($this->_registryAlias === null) {
$this->_registryAlias = $this->getAlias();
}
return $this->_registryAlias;
}
/**
* Returns the table registry key used to create this table instance or sets one.
*
* @deprecated 3.4.0 Use setRegistryAlias()/getRegistryAlias() instead.
* @param string|null $registryAlias the key used to access this object
* @return string
*/
public function registryAlias($registryAlias = null)
{
if ($registryAlias !== null) {
$this->setRegistryAlias($registryAlias);
}
return $this->getRegistryAlias();
}
/**
* Sets the connection instance.
*
* @param \Cake\Datasource\ConnectionInterface $connection The connection instance
* @return $this
*/
public function setConnection(ConnectionInterface $connection)
{
$this->_connection = $connection;
return $this;
}
/**
* Returns the connection instance.
*
* @return \Cake\Datasource\ConnectionInterface
*/
public function getConnection()
{
return $this->_connection;
}
/**
* Returns the connection instance or sets a new one
*
* @deprecated 3.4.0 Use setConnection()/getConnection() instead.
* @param \Cake\Datasource\ConnectionInterface|null $connection The new connection instance
* @return \Cake\Datasource\ConnectionInterface
*/
public function connection(ConnectionInterface $connection = null)
{
if ($connection !== null) {
$this->setConnection($connection);
}
return $this->getConnection();
}
/**
* Returns the schema table object describing this table's properties.
*
* @return \Cake\Database\Schema\TableSchema
*/
public function getSchema()
{
if ($this->_schema === null) {
$this->_schema = $this->_initializeSchema(
$this->getConnection()
->getSchemaCollection()
->describe($this->getTable())
);
}
return $this->_schema;
}
/**
* Sets the schema table object describing this table's properties.
*
* If an array is passed, a new TableSchema will be constructed
* out of it and used as the schema for this table.
*
* @param array|\Cake\Database\Schema\TableSchema $schema Schema to be used for this table
* @return $this
*/
public function setSchema($schema)
{
if (is_array($schema)) {
$constraints = [];
if (isset($schema['_constraints'])) {
$constraints = $schema['_constraints'];
unset($schema['_constraints']);
}
$schema = new TableSchema($this->getTable(), $schema);
foreach ($constraints as $name => $value) {
$schema->addConstraint($name, $value);
}
}
$this->_schema = $schema;
return $this;
}
/**
* Returns the schema table object describing this table's properties.
*
* If a TableSchema is passed, it will be used for this table
* instead of the default one.
*
* If an array is passed, a new TableSchema will be constructed
* out of it and used as the schema for this table.
*
* @deprecated 3.4.0 Use setSchema()/getSchema() instead.
* @param array|\Cake\Database\Schema\TableSchema|null $schema New schema to be used for this table
* @return \Cake\Database\Schema\TableSchema
*/
public function schema($schema = null)
{
if ($schema !== null) {
$this->setSchema($schema);
}
return $this->getSchema();
}
/**
* Override this function in order to alter the schema used by this table.
* This function is only called after fetching the schema out of the database.
* If you wish to provide your own schema to this table without touching the
* database, you can override schema() or inject the definitions though that
* method.
*
* ### Example:
*
* ```
* protected function _initializeSchema(\Cake\Database\Schema\TableSchema $schema) {
* $schema->columnType('preferences', 'json');
* return $schema;
* }
* ```
*
* @param \Cake\Database\Schema\TableSchema $schema The table definition fetched from database.
* @return \Cake\Database\Schema\TableSchema the altered schema
* @api
*/
protected function _initializeSchema(TableSchema $schema)
{
return $schema;
}
/**
* Test to see if a Table has a specific field/column.
*
* Delegates to the schema object and checks for column presence
* using the Schema\Table instance.
*
* @param string $field The field to check for.
* @return bool True if the field exists, false if it does not.
*/
public function hasField($field)
{
$schema = $this->getSchema();
return $schema->column($field) !== null;
}
/**
* Sets the primary key field name.
*
* @param string|array $key Sets a new name to be used as primary key
* @return $this
*/
public function setPrimaryKey($key)
{
$this->_primaryKey = $key;
return $this;
}
/**
* Returns the primary key field name.
*
* @return string|array
*/
public function getPrimaryKey()
{
if ($this->_primaryKey === null) {
$key = (array)$this->getSchema()->primaryKey();
if (count($key) === 1) {
$key = $key[0];
}
$this->_primaryKey = $key;
}
return $this->_primaryKey;
}
/**
* Returns the primary key field name or sets a new one
*
* @deprecated 3.4.0 Use setPrimaryKey()/getPrimaryKey() instead.
* @param string|array|null $key Sets a new name to be used as primary key
* @return string|array
*/
public function primaryKey($key = null)
{
if ($key !== null) {
$this->setPrimaryKey($key);
}
return $this->getPrimaryKey();
}
/**
* Sets the display field.
*
* @param string $key Name to be used as display field.
* @return $this
*/
public function setDisplayField($key)
{
$this->_displayField = $key;
return $this;
}
/**
* Returns the display field.
*
* @return string
*/
public function getDisplayField()
{
if ($this->_displayField === null) {
$schema = $this->getSchema();
$primary = (array)$this->getPrimaryKey();
$this->_displayField = array_shift($primary);
if ($schema->column('title')) {
$this->_displayField = 'title';
}
if ($schema->column('name')) {
$this->_displayField = 'name';
}
}
return $this->_displayField;
}
/**
* Returns the display field or sets a new one
*
* @deprecated 3.4.0 Use setDisplayField()/getDisplayField() instead.
* @param string|null $key sets a new name to be used as display field
* @return string
*/
public function displayField($key = null)
{
if ($key !== null) {
return $this->setDisplayField($key);
}
return $this->getDisplayField();
}
/**
* Returns the class used to hydrate rows for this table.
*
* @return string
*/
public function getEntityClass()
{
if (!$this->_entityClass) {
$default = '\Cake\ORM\Entity';
$self = get_called_class();
$parts = explode('\\', $self);
if ($self === __CLASS__ || count($parts) < 3) {
return $this->_entityClass = $default;
}
$alias = Inflector::singularize(substr(array_pop($parts), 0, -5));
$name = implode('\\', array_slice($parts, 0, -1)) . '\Entity\\' . $alias;
if (!class_exists($name)) {
return $this->_entityClass = $default;
}
$class = App::className($name, 'Model/Entity');
if (!$class) {
throw new MissingEntityException([$name]);
}
$this->_entityClass = $class;
}
return $this->_entityClass;
}
/**
* Sets the class used to hydrate rows for this table.
*
* @param string $name The name of the class to use
* @throws \Cake\ORM\Exception\MissingEntityException when the entity class cannot be found
* @return $this
*/
public function setEntityClass($name)
{
$class = App::className($name, 'Model/Entity');
if (!$class) {
throw new MissingEntityException([$name]);
}
$this->_entityClass = $class;
return $this;
}
/**
* Returns the class used to hydrate rows for this table or sets
* a new one
*
* @deprecated 3.4.0 Use setEntityClass()/getEntityClass() instead.
* @param string|null $name The name of the class to use
* @throws \Cake\ORM\Exception\MissingEntityException when the entity class cannot be found
* @return string
*/
public function entityClass($name = null)
{
if ($name !== null) {
$this->setEntityClass($name);
}
return $this->getEntityClass();
}
/**
* Add a behavior.
*
* Adds a behavior to this table's behavior collection. Behaviors
* provide an easy way to create horizontally re-usable features
* that can provide trait like functionality, and allow for events
* to be listened to.
*
* Example:
*
* Load a behavior, with some settings.
*
* ```
* $this->addBehavior('Tree', ['parent' => 'parentId']);
* ```
*
* Behaviors are generally loaded during Table::initialize().
*
* @param string $name The name of the behavior. Can be a short class reference.
* @param array $options The options for the behavior to use.
* @return void
* @throws \RuntimeException If a behavior is being reloaded.
* @see \Cake\ORM\Behavior
*/
public function addBehavior($name, array $options = [])
{
$this->_behaviors->load($name, $options);
}
/**
* Removes a behavior from this table's behavior registry.
*
* Example:
*
* Remove a behavior from this table.
*
* ```
* $this->removeBehavior('Tree');
* ```
*
* @param string $name The alias that the behavior was added with.
* @return void
* @see \Cake\ORM\Behavior
*/
public function removeBehavior($name)
{
$this->_behaviors->unload($name);
}
/**
* Returns the behavior registry for this table.
*
* @return \Cake\ORM\BehaviorRegistry The BehaviorRegistry instance.
*/
public function behaviors()
{
return $this->_behaviors;
}
/**
* Check if a behavior with the given alias has been loaded.
*
* @param string $name The behavior alias to check.
* @return bool Whether or not the behavior exists.
*/
public function hasBehavior($name)
{
return $this->_behaviors->has($name);
}
/**
* Returns an association object configured for the specified alias if any
*
* @param string $name the alias used for the association.
* @return \Cake\ORM\Association|null Either the association or null.
*/
public function association($name)
{
return $this->_associations->get($name);
}
/**
* Get the associations collection for this table.
*
* @return \Cake\ORM\AssociationCollection The collection of association objects.
*/
public function associations()
{
return $this->_associations;
}
/**
* Setup multiple associations.
*
* It takes an array containing set of table names indexed by association type
* as argument:
*
* ```
* $this->Posts->addAssociations([
* 'belongsTo' => [
* 'Users' => ['className' => 'App\Model\Table\UsersTable']
* ],
* 'hasMany' => ['Comments'],
* 'belongsToMany' => ['Tags']
* ]);
* ```
*
* Each association type accepts multiple associations where the keys
* are the aliases, and the values are association config data. If numeric
* keys are used the values will be treated as association aliases.
*
* @param array $params Set of associations to bind (indexed by association type)
* @return void
* @see \Cake\ORM\Table::belongsTo()
* @see \Cake\ORM\Table::hasOne()
* @see \Cake\ORM\Table::hasMany()
* @see \Cake\ORM\Table::belongsToMany()
*/
public function addAssociations(array $params)
{
foreach ($params as $assocType => $tables) {
foreach ($tables as $associated => $options) {
if (is_numeric($associated)) {
$associated = $options;
$options = [];
}
$this->{$assocType}($associated, $options);
}
}
}
/**
* Creates a new BelongsTo association between this table and a target
* table. A "belongs to" association is a N-1 relationship where this table
* is the N side, and where there is a single associated record in the target
* table for each one in this table.
*
* Target table can be inferred by its name, which is provided in the
* first argument, or you can either pass the to be instantiated or
* an instance of it directly.
*
* The options array accept the following keys:
*
* - className: The class name of the target table object
* - targetTable: An instance of a table object to be used as the target table
* - foreignKey: The name of the field to use as foreign key, if false none
* will be used
* - conditions: array with a list of conditions to filter the join with
* - joinType: The type of join to be used (e.g. INNER)
* - strategy: The loading strategy to use. 'join' and 'select' are supported.
* - finder: The finder method to use when loading records from this association.
* Defaults to 'all'. When the strategy is 'join', only the fields, containments,
* and where conditions will be used from the finder.
*
* This method will return the association object that was built.
*
* @param string $associated the alias for the target table. This is used to
* uniquely identify the association
* @param array $options list of options to configure the association definition
* @return \Cake\ORM\Association\BelongsTo
*/
public function belongsTo($associated, array $options = [])
{
$options += ['sourceTable' => $this];
$association = new BelongsTo($associated, $options);
return $this->_associations->add($association->getName(), $association);
}
/**
* Creates a new HasOne association between this table and a target
* table. A "has one" association is a 1-1 relationship.
*
* Target table can be inferred by its name, which is provided in the
* first argument, or you can either pass the class name to be instantiated or
* an instance of it directly.
*
* The options array accept the following keys:
*
* - className: The class name of the target table object
* - targetTable: An instance of a table object to be used as the target table
* - foreignKey: The name of the field to use as foreign key, if false none
* will be used
* - dependent: Set to true if you want CakePHP to cascade deletes to the
* associated table when an entity is removed on this table. The delete operation
* on the associated table will not cascade further. To get recursive cascades enable
* `cascadeCallbacks` as well. Set to false if you don't want CakePHP to remove
* associated data, or when you are using database constraints.
* - cascadeCallbacks: Set to true if you want CakePHP to fire callbacks on
* cascaded deletes. If false the ORM will use deleteAll() to remove data.
* When true records will be loaded and then deleted.
* - conditions: array with a list of conditions to filter the join with
* - joinType: The type of join to be used (e.g. LEFT)
* - strategy: The loading strategy to use. 'join' and 'select' are supported.
* - finder: The finder method to use when loading records from this association.
* Defaults to 'all'. When the strategy is 'join', only the fields, containments,
* and where conditions will be used from the finder.
*
* This method will return the association object that was built.
*