-
Notifications
You must be signed in to change notification settings - Fork 18
/
Association.php
1258 lines (1117 loc) · 39.7 KB
/
Association.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
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\ORM;
use Cake\Collection\Collection;
use Cake\Core\App;
use Cake\Core\ConventionsTrait;
use Cake\Database\Expression\IdentifierExpression;
use Cake\Datasource\EntityInterface;
use Cake\Datasource\ResultSetDecorator;
use Cake\ORM\Locator\LocatorAwareTrait;
use Cake\Utility\Inflector;
use Closure;
use InvalidArgumentException;
use RuntimeException;
/**
* An Association is a relationship established between two tables and is used
* to configure and customize the way interconnected records are retrieved.
*
* @mixin \Cake\ORM\Table
*/
abstract class Association
{
use ConventionsTrait;
use LocatorAwareTrait;
/**
* Strategy name to use joins for fetching associated records
*
* @var string
*/
public const STRATEGY_JOIN = 'join';
/**
* Strategy name to use a subquery for fetching associated records
*
* @var string
*/
public const STRATEGY_SUBQUERY = 'subquery';
/**
* Strategy name to use a select for fetching associated records
*
* @var string
*/
public const STRATEGY_SELECT = 'select';
/**
* Association type for one to one associations.
*
* @var string
*/
public const ONE_TO_ONE = 'oneToOne';
/**
* Association type for one to many associations.
*
* @var string
*/
public const ONE_TO_MANY = 'oneToMany';
/**
* Association type for many to many associations.
*
* @var string
*/
public const MANY_TO_MANY = 'manyToMany';
/**
* Association type for many to one associations.
*
* @var string
*/
public const MANY_TO_ONE = 'manyToOne';
/**
* Name given to the association, it usually represents the alias
* assigned to the target associated table
*
* @var string
*/
protected $_name;
/**
* The class name of the target table object
*
* @var string
*/
protected $_className;
/**
* The field name in the owning side table that is used to match with the foreignKey
*
* @var string|string[]|null
*/
protected $_bindingKey;
/**
* The name of the field representing the foreign key to the table to load
*
* @var string|string[]
*/
protected $_foreignKey;
/**
* A list of conditions to be always included when fetching records from
* the target association
*
* @var array|\Closure
*/
protected $_conditions = [];
/**
* Whether the records on the target table are dependent on the source table,
* often used to indicate that records should be removed if the owning record in
* the source table is deleted.
*
* @var bool
*/
protected $_dependent = false;
/**
* Whether or not cascaded deletes should also fire callbacks.
*
* @var bool
*/
protected $_cascadeCallbacks = false;
/**
* Source table instance
*
* @var \Cake\ORM\Table
*/
protected $_sourceTable;
/**
* Target table instance
*
* @var \Cake\ORM\Table
*/
protected $_targetTable;
/**
* The type of join to be used when adding the association to a query
*
* @var string
*/
protected $_joinType = Query::JOIN_TYPE_LEFT;
/**
* The property name that should be filled with data from the target table
* in the source table record.
*
* @var string
*/
protected $_propertyName;
/**
* The strategy name to be used to fetch associated records. Some association
* types might not implement but one strategy to fetch records.
*
* @var string
*/
protected $_strategy = self::STRATEGY_JOIN;
/**
* The default finder name to use for fetching rows from the target table
* With array value, finder name and default options are allowed.
*
* @var string|array
*/
protected $_finder = 'all';
/**
* Valid strategies for this association. Subclasses can narrow this down.
*
* @var string[]
*/
protected $_validStrategies = [
self::STRATEGY_JOIN,
self::STRATEGY_SELECT,
self::STRATEGY_SUBQUERY,
];
/**
* Constructor. Subclasses can override _options function to get the original
* list of passed options if expecting any other special key
*
* @param string $alias The name given to the association
* @param array $options A list of properties to be set on this object
*/
public function __construct(string $alias, array $options = [])
{
$defaults = [
'cascadeCallbacks',
'className',
'conditions',
'dependent',
'finder',
'bindingKey',
'foreignKey',
'joinType',
'tableLocator',
'propertyName',
'sourceTable',
'targetTable',
];
foreach ($defaults as $property) {
if (isset($options[$property])) {
$this->{'_' . $property} = $options[$property];
}
}
if (empty($this->_className)) {
$this->_className = $alias;
}
[, $name] = pluginSplit($alias);
$this->_name = $name;
$this->_options($options);
if (!empty($options['strategy'])) {
$this->setStrategy($options['strategy']);
}
}
/**
* Sets the name for this association, usually the alias
* assigned to the target associated table
*
* @param string $name Name to be assigned
* @return $this
*/
public function setName(string $name)
{
if ($this->_targetTable !== null) {
$alias = $this->_targetTable->getAlias();
if ($alias !== $name) {
throw new InvalidArgumentException(sprintf(
'Association name "%s" does not match target table alias "%s".',
$name,
$alias
));
}
}
$this->_name = $name;
return $this;
}
/**
* Gets the name for this association, usually the alias
* assigned to the target associated table
*
* @return string
*/
public function getName(): string
{
return $this->_name;
}
/**
* Sets whether or not cascaded deletes should also fire callbacks.
*
* @param bool $cascadeCallbacks cascade callbacks switch value
* @return $this
*/
public function setCascadeCallbacks(bool $cascadeCallbacks)
{
$this->_cascadeCallbacks = $cascadeCallbacks;
return $this;
}
/**
* Gets whether or not cascaded deletes should also fire callbacks.
*
* @return bool
*/
public function getCascadeCallbacks(): bool
{
return $this->_cascadeCallbacks;
}
/**
* Sets the class name of the target table object.
*
* @param string $className Class name to set.
* @return $this
* @throws \InvalidArgumentException In case the class name is set after the target table has been
* resolved, and it doesn't match the target table's class name.
*/
public function setClassName(string $className)
{
if (
$this->_targetTable !== null &&
get_class($this->_targetTable) !== App::className($className, 'Model/Table', 'Table')
) {
throw new InvalidArgumentException(sprintf(
'The class name "%s" doesn\'t match the target table class name of "%s".',
$className,
get_class($this->_targetTable)
));
}
$this->_className = $className;
return $this;
}
/**
* Gets the class name of the target table object.
*
* @return string
*/
public function getClassName(): string
{
return $this->_className;
}
/**
* Sets the table instance for the source side of the association.
*
* @param \Cake\ORM\Table $table the instance to be assigned as source side
* @return $this
*/
public function setSource(Table $table)
{
$this->_sourceTable = $table;
return $this;
}
/**
* Gets the table instance for the source side of the association.
*
* @return \Cake\ORM\Table
*/
public function getSource(): Table
{
return $this->_sourceTable;
}
/**
* Sets the table instance for the target side of the association.
*
* @param \Cake\ORM\Table $table the instance to be assigned as target side
* @return $this
*/
public function setTarget(Table $table)
{
$this->_targetTable = $table;
return $this;
}
/**
* Gets the table instance for the target side of the association.
*
* @return \Cake\ORM\Table
*/
public function getTarget(): Table
{
if ($this->_targetTable === null) {
if (strpos($this->_className, '.')) {
[$plugin] = pluginSplit($this->_className, true);
$registryAlias = (string)$plugin . $this->_name;
} else {
$registryAlias = $this->_name;
}
$tableLocator = $this->getTableLocator();
$config = [];
$exists = $tableLocator->exists($registryAlias);
if (!$exists) {
$config = ['className' => $this->_className];
}
$this->_targetTable = $tableLocator->get($registryAlias, $config);
if ($exists) {
$className = App::className($this->_className, 'Model/Table', 'Table') ?: Table::class;
if (!$this->_targetTable instanceof $className) {
$errorMessage = '%s association "%s" of type "%s" to "%s" doesn\'t match the expected class "%s". ';
$errorMessage .= 'You can\'t have an association of the same name with a different target ';
$errorMessage .= '"className" option anywhere in your app.';
throw new RuntimeException(sprintf(
$errorMessage,
$this->_sourceTable === null ? 'null' : get_class($this->_sourceTable),
$this->getName(),
$this->type(),
get_class($this->_targetTable),
$className
));
}
}
}
return $this->_targetTable;
}
/**
* Sets a list of conditions to be always included when fetching records from
* the target association.
*
* @param array|\Closure $conditions list of conditions to be used
* @see \Cake\Database\Query::where() for examples on the format of the array
* @return \Cake\ORM\Association
*/
public function setConditions($conditions)
{
$this->_conditions = $conditions;
return $this;
}
/**
* Gets a list of conditions to be always included when fetching records from
* the target association.
*
* @see \Cake\Database\Query::where() for examples on the format of the array
* @return array|\Closure
*/
public function getConditions()
{
return $this->_conditions;
}
/**
* Sets the name of the field representing the binding field with the target table.
* When not manually specified the primary key of the owning side table is used.
*
* @param string|string[] $key the table field or fields to be used to link both tables together
* @return $this
*/
public function setBindingKey($key)
{
$this->_bindingKey = $key;
return $this;
}
/**
* Gets the name of the field representing the binding field with the target table.
* When not manually specified the primary key of the owning side table is used.
*
* @return string|string[]
*/
public function getBindingKey()
{
if ($this->_bindingKey === null) {
$this->_bindingKey = $this->isOwningSide($this->getSource()) ?
$this->getSource()->getPrimaryKey() :
$this->getTarget()->getPrimaryKey();
}
return $this->_bindingKey;
}
/**
* Gets the name of the field representing the foreign key to the target table.
*
* @return string|string[]
*/
public function getForeignKey()
{
return $this->_foreignKey;
}
/**
* Sets the name of the field representing the foreign key to the target table.
*
* @param string|string[] $key the key or keys to be used to link both tables together
* @return $this
*/
public function setForeignKey($key)
{
$this->_foreignKey = $key;
return $this;
}
/**
* Sets whether the records on the target table are dependent on the source table.
*
* This is primarily used to indicate that records should be removed if the owning record in
* the source table is deleted.
*
* If no parameters are passed the current setting is returned.
*
* @param bool $dependent Set the dependent mode. Use null to read the current state.
* @return $this
*/
public function setDependent(bool $dependent)
{
$this->_dependent = $dependent;
return $this;
}
/**
* Sets whether the records on the target table are dependent on the source table.
*
* This is primarily used to indicate that records should be removed if the owning record in
* the source table is deleted.
*
* @return bool
*/
public function getDependent(): bool
{
return $this->_dependent;
}
/**
* Whether this association can be expressed directly in a query join
*
* @param array $options custom options key that could alter the return value
* @return bool
*/
public function canBeJoined(array $options = []): bool
{
$strategy = $options['strategy'] ?? $this->getStrategy();
return $strategy === $this::STRATEGY_JOIN;
}
/**
* Sets the type of join to be used when adding the association to a query.
*
* @param string $type the join type to be used (e.g. INNER)
* @return $this
*/
public function setJoinType(string $type)
{
$this->_joinType = $type;
return $this;
}
/**
* Gets the type of join to be used when adding the association to a query.
*
* @return string
*/
public function getJoinType(): string
{
return $this->_joinType;
}
/**
* Sets the property name that should be filled with data from the target table
* in the source table record.
*
* @param string $name The name of the association property. Use null to read the current value.
* @return $this
*/
public function setProperty(string $name)
{
$this->_propertyName = $name;
return $this;
}
/**
* Gets the property name that should be filled with data from the target table
* in the source table record.
*
* @return string
*/
public function getProperty(): string
{
if (!$this->_propertyName) {
$this->_propertyName = $this->_propertyName();
if (in_array($this->_propertyName, $this->_sourceTable->getSchema()->columns(), true)) {
$msg = 'Association property name "%s" clashes with field of same name of table "%s".' .
' You should explicitly specify the "propertyName" option.';
trigger_error(
sprintf($msg, $this->_propertyName, $this->_sourceTable->getTable()),
E_USER_WARNING
);
}
}
return $this->_propertyName;
}
/**
* Returns default property name based on association name.
*
* @return string
*/
protected function _propertyName(): string
{
[, $name] = pluginSplit($this->_name);
return Inflector::underscore($name);
}
/**
* Sets the strategy name to be used to fetch associated records. Keep in mind
* that some association types might not implement but a default strategy,
* rendering any changes to this setting void.
*
* @param string $name The strategy type. Use null to read the current value.
* @return $this
* @throws \InvalidArgumentException When an invalid strategy is provided.
*/
public function setStrategy(string $name)
{
if (!in_array($name, $this->_validStrategies, true)) {
throw new InvalidArgumentException(sprintf(
'Invalid strategy "%s" was provided. Valid options are (%s).',
$name,
implode(', ', $this->_validStrategies)
));
}
$this->_strategy = $name;
return $this;
}
/**
* Gets the strategy name to be used to fetch associated records. Keep in mind
* that some association types might not implement but a default strategy,
* rendering any changes to this setting void.
*
* @return string
*/
public function getStrategy(): string
{
return $this->_strategy;
}
/**
* Gets the default finder to use for fetching rows from the target table.
*
* @return string|array
*/
public function getFinder()
{
return $this->_finder;
}
/**
* Sets the default finder to use for fetching rows from the target table.
*
* @param string|array $finder the finder name to use or array of finder name and option.
* @return $this
*/
public function setFinder($finder)
{
$this->_finder = $finder;
return $this;
}
/**
* Override this function to initialize any concrete association class, it will
* get passed the original list of options used in the constructor
*
* @param array $options List of options used for initialization
* @return void
*/
protected function _options(array $options): void
{
}
/**
* Alters a Query object to include the associated target table data in the final
* result
*
* The options array accept the following keys:
*
* - includeFields: Whether to include target model fields in the result or not
* - 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, this
* will be merged with any conditions originally configured for this association
* - fields: a list of fields in the target table to include in the result
* - type: The type of join to be used (e.g. INNER)
* the records found on this association
* - aliasPath: A dot separated string representing the path of association names
* followed from the passed query main table to this association.
* - propertyPath: A dot separated string representing the path of association
* properties to be followed from the passed query main entity to this
* association
* - joinType: The SQL join type to use in the query.
* - negateMatch: Will append a condition to the passed query for excluding matches.
* with this association.
*
* @param \Cake\ORM\Query $query the query to be altered to include the target table data
* @param array $options Any extra options or overrides to be taken in account
* @return void
* @throws \RuntimeException if the query builder passed does not return a query
* object
*/
public function attachTo(Query $query, array $options = []): void
{
$target = $this->getTarget();
$joinType = empty($options['joinType']) ? $this->getJoinType() : $options['joinType'];
$table = $target->getTable();
$options += [
'includeFields' => true,
'foreignKey' => $this->getForeignKey(),
'conditions' => [],
'fields' => [],
'type' => $joinType,
'table' => $table,
'finder' => $this->getFinder(),
];
if (!empty($options['foreignKey'])) {
$joinCondition = $this->_joinCondition($options);
if ($joinCondition) {
$options['conditions'][] = $joinCondition;
}
}
[$finder, $opts] = $this->_extractFinder($options['finder']);
$dummy = $this
->find($finder, $opts)
->eagerLoaded(true);
if (!empty($options['queryBuilder'])) {
$dummy = $options['queryBuilder']($dummy);
if (!($dummy instanceof Query)) {
throw new RuntimeException(sprintf(
'Query builder for association "%s" did not return a query',
$this->getName()
));
}
}
if (
!empty($options['matching']) &&
$this->_strategy === static::STRATEGY_JOIN &&
$dummy->getContain()
) {
throw new RuntimeException(
"`{$this->getName()}` association cannot contain() associations when using JOIN strategy."
);
}
$dummy->where($options['conditions']);
$this->_dispatchBeforeFind($dummy);
$joinOptions = ['table' => 1, 'conditions' => 1, 'type' => 1];
$options['conditions'] = $dummy->clause('where');
$query->join([$this->_name => array_intersect_key($options, $joinOptions)]);
$this->_appendFields($query, $dummy, $options);
$this->_formatAssociationResults($query, $dummy, $options);
$this->_bindNewAssociations($query, $dummy, $options);
$this->_appendNotMatching($query, $options);
}
/**
* Conditionally adds a condition to the passed Query that will make it find
* records where there is no match with this association.
*
* @param \Cake\ORM\Query $query The query to modify
* @param array $options Options array containing the `negateMatch` key.
* @return void
*/
protected function _appendNotMatching(Query $query, array $options): void
{
$target = $this->_targetTable;
if (!empty($options['negateMatch'])) {
$primaryKey = $query->aliasFields((array)$target->getPrimaryKey(), $this->_name);
$query->andWhere(function ($exp) use ($primaryKey) {
array_map([$exp, 'isNull'], $primaryKey);
return $exp;
});
}
}
/**
* Correctly nests a result row associated values into the correct array keys inside the
* source results.
*
* @param array $row The row to transform
* @param string $nestKey The array key under which the results for this association
* should be found
* @param bool $joined Whether or not the row is a result of a direct join
* with this association
* @param string|null $targetProperty The property name in the source results where the association
* data shuld be nested in. Will use the default one if not provided.
* @return array
*/
public function transformRow(array $row, string $nestKey, bool $joined, ?string $targetProperty = null): array
{
$sourceAlias = $this->getSource()->getAlias();
$nestKey = $nestKey ?: $this->_name;
$targetProperty = $targetProperty ?: $this->getProperty();
if (isset($row[$sourceAlias])) {
$row[$sourceAlias][$targetProperty] = $row[$nestKey];
unset($row[$nestKey]);
}
return $row;
}
/**
* Returns a modified row after appending a property for this association
* with the default empty value according to whether the association was
* joined or fetched externally.
*
* @param array $row The row to set a default on.
* @param bool $joined Whether or not the row is a result of a direct join
* with this association
* @return array
*/
public function defaultRowValue(array $row, bool $joined): array
{
$sourceAlias = $this->getSource()->getAlias();
if (isset($row[$sourceAlias])) {
$row[$sourceAlias][$this->getProperty()] = null;
}
return $row;
}
/**
* Proxies the finding operation to the target table's find method
* and modifies the query accordingly based of this association
* configuration
*
* @param string|array|null $type the type of query to perform, if an array is passed,
* it will be interpreted as the `$options` parameter
* @param array $options The options to for the find
* @see \Cake\ORM\Table::find()
* @return \Cake\ORM\Query
*/
public function find($type = null, array $options = []): Query
{
$type = $type ?: $this->getFinder();
[$type, $opts] = $this->_extractFinder($type);
return $this->getTarget()
->find($type, $options + $opts)
->where($this->getConditions());
}
/**
* Proxies the operation to the target table's exists method after
* appending the default conditions for this association
*
* @param array|\Closure|\Cake\Database\ExpressionInterface $conditions The conditions to use
* for checking if any record matches.
* @see \Cake\ORM\Table::exists()
* @return bool
*/
public function exists($conditions): bool
{
$conditions = $this->find()
->where($conditions)
->clause('where');
return $this->getTarget()->exists($conditions);
}
/**
* Proxies the update operation to the target table's updateAll method
*
* @param array $fields A hash of field => new value.
* @param mixed $conditions Conditions to be used, accepts anything Query::where()
* can take.
* @see \Cake\ORM\Table::updateAll()
* @return int Count Returns the affected rows.
*/
public function updateAll(array $fields, $conditions): int
{
$expression = $this->find()
->where($conditions)
->clause('where');
return $this->getTarget()->updateAll($fields, $expression);
}
/**
* Proxies the delete operation to the target table's deleteAll method
*
* @param mixed $conditions Conditions to be used, accepts anything Query::where()
* can take.
* @return int Returns the number of affected rows.
* @see \Cake\ORM\Table::deleteAll()
*/
public function deleteAll($conditions): int
{
$expression = $this->find()
->where($conditions)
->clause('where');
return $this->getTarget()->deleteAll($expression);
}
/**
* Returns true if the eager loading process will require a set of the owning table's
* binding keys in order to use them as a filter in the finder query.
*
* @param array $options The options containing the strategy to be used.
* @return bool true if a list of keys will be required
*/
public function requiresKeys(array $options = []): bool
{
$strategy = $options['strategy'] ?? $this->getStrategy();
return $strategy === static::STRATEGY_SELECT;
}
/**
* Triggers beforeFind on the target table for the query this association is
* attaching to
*
* @param \Cake\ORM\Query $query the query this association is attaching itself to
* @return void
*/
protected function _dispatchBeforeFind(Query $query): void
{
$query->triggerBeforeFind();
}
/**
* Helper function used to conditionally append fields to the select clause of
* a query from the fields found in another query object.
*
* @param \Cake\ORM\Query $query the query that will get the fields appended to
* @param \Cake\ORM\Query $surrogate the query having the fields to be copied from
* @param array $options options passed to the method `attachTo`
* @return void
*/
protected function _appendFields(Query $query, Query $surrogate, array $options): void
{
if ($query->getEagerLoader()->isAutoFieldsEnabled() === false) {
return;
}
$fields = $surrogate->clause('select') ?: $options['fields'];
$target = $this->_targetTable;
$autoFields = $surrogate->isAutoFieldsEnabled();
if (empty($fields) && !$autoFields) {
if ($options['includeFields'] && ($fields === null || $fields !== false)) {
$fields = $target->getSchema()->columns();
}
}
if ($autoFields === true) {
$fields = array_filter((array)$fields);
$fields = array_merge($fields, $target->getSchema()->columns());
}
if ($fields) {
$query->select($query->aliasFields($fields, $this->_name));
}
$query->addDefaultTypes($target);
}
/**
* Adds a formatter function to the passed `$query` if the `$surrogate` query
* declares any other formatter. Since the `$surrogate` query correspond to
* the associated target table, the resulting formatter will be the result of
* applying the surrogate formatters to only the property corresponding to
* such table.
*
* @param \Cake\ORM\Query $query the query that will get the formatter applied to
* @param \Cake\ORM\Query $surrogate the query having formatters for the associated
* target table.
* @param array $options options passed to the method `attachTo`
* @return void
*/
protected function _formatAssociationResults(Query $query, Query $surrogate, array $options): void
{
$formatters = $surrogate->getResultFormatters();
if (!$formatters || empty($options['propertyPath'])) {
return;
}