AuthorsTable.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * Redistributions of files must retain the above copyright notice
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @since 3.0.0
  12. * @license https://opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace TestApp\Model\Table;
  15. use Cake\ORM\Query\SelectQuery;
  16. use Cake\ORM\Table;
  17. /**
  18. * Author table class
  19. */
  20. class AuthorsTable extends Table
  21. {
  22. /**
  23. * @param array<string, mixed> $config
  24. * @return void
  25. */
  26. public function initialize(array $config): void
  27. {
  28. $this->hasMany('Articles');
  29. }
  30. /**
  31. * @param \Cake\ORM\Query\SelectQuery $query
  32. * @param int|null $authorId
  33. * @return \Cake\ORM\Query\SelectQuery
  34. */
  35. public function findByAuthor(SelectQuery $query, ?int $authorId = null): SelectQuery
  36. {
  37. if ($authorId !== null) {
  38. $query->where(['Articles.id' => $authorId]);
  39. }
  40. return $query;
  41. }
  42. /**
  43. * Finder that applies a formatter to test dirty associations
  44. *
  45. * @param \Cake\ORM\Query\SelectQuery $query The query
  46. * @param array<string, mixed> $options The options
  47. * @return \Cake\ORM\Query\SelectQuery
  48. */
  49. public function findFormatted(SelectQuery $query, array $options = []): SelectQuery
  50. {
  51. return $query->formatResults(function ($results) {
  52. return $results->map(function ($author) {
  53. $author->formatted = $author->name . '!!';
  54. return $author;
  55. });
  56. });
  57. }
  58. /**
  59. * Finder that accepts an option via a typed parameter.
  60. *
  61. * @param \Cake\ORM\Query\SelectQuery $query The query
  62. * @param int $id Author ID
  63. * @return \Cake\ORM\Query\SelectQuery
  64. */
  65. public function findWithIdArgument(SelectQuery $query, int $id): SelectQuery
  66. {
  67. return $query->where(['id' => $id]);
  68. }
  69. }