Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: [CakePHP] asocjacja wiele do wielu - find('list')
Forum PHP.pl > Forum > PHP > Frameworki
mkudej
Witam ponownie.
Zaczełem ostatnio swoją przygode z CakePHP, chcę napisać prostą aplickacje do wymiany gier między użytkownikami.
Mam tabele users - każdy user może mieć kilka platform.
Mam również tabele userGames - do każdej z gier przypisana jest jedna platforma.
No i oczywiście tabela platforms - w której zpisana jest nazwa i id platformy.
Plus do tego tablica asocjacji wiele do wielu platforms_users - która ma pola id, platform_id, user_id
Oczywiście mam utworzone za pomocą piekarni modele. Wydaje mi się że wszystkie asocjacje są w porzadku.
Teraz mój problem polega na tym że chciałbym wylistować metoda find('list') wszystkie platformy które należą do użytkownika o id 1.

Więc na chłopski rozum zapytanie:
  1. SELECT platforms.name, platforms.id FROM platforms LEFT JOIN platforms_users ON platforms_users.platform_id=platforms.id WHERE platforms_users.user_id=1


Działa idealnie w phpmyadminie.
Tylko jak teraz to zrobić w cake?
Próbowałem już wszystkiego...

Między innymi:
Kontroler users
  1. $this->User->Platform->find('list', array('conditions', array('User.id'=>'1')));


I kilka takich kombinacji, również w kontrolerze platforms...
Ale za nic nie mogłem tego wybrać...
Proszę o pomoc...

Załączam modele
  1. class Platform extends AppModel {
  2.  
  3. public $displayField = 'name';
  4.  
  5. public $hasMany = array(
  6. 'UserGame' => array(
  7. 'className' => 'UserGame',
  8. 'foreignKey' => 'platform_id',
  9. 'conditions' => '',
  10. 'fields' => '',
  11. 'order' => ''
  12. )
  13. );
  14.  
  15. public $hasAndBelongsToMany = array(
  16. 'User' => array(
  17. 'className' => 'User',
  18. 'joinTable' => 'platforms_users',
  19. 'foreignKey' => 'platform_id',
  20. 'associationForeignKey' => 'user_id',
  21. 'unique' => 'keepExisting',
  22. 'conditions' => '',
  23. 'fields' => '',
  24. 'order' => '',
  25. 'limit' => '',
  26. 'offset' => '',
  27. 'finderQuery' => '',
  28. 'deleteQuery' => '',
  29. 'insertQuery' => ''
  30. )
  31. );
  32.  
  33. }


  1. class User extends AppModel {
  2.  
  3. /**
  4.   * Display field
  5.   *
  6.   * @var string
  7.   */
  8. public $displayField = 'name';
  9.  
  10.  
  11. //The Associations below have been created with all possible keys, those that are not needed can be removed
  12.  
  13. /**
  14.   * hasMany associations
  15.   *
  16.   * @var array
  17.   */
  18. public $hasMany = array(
  19. 'UserGame' => array(
  20. 'className' => 'UserGame',
  21. 'foreignKey' => 'user_id',
  22. 'dependent' => false,
  23. 'conditions' => '',
  24. 'fields' => '',
  25. 'order' => '',
  26. 'limit' => '',
  27. 'offset' => '',
  28. 'exclusive' => '',
  29. 'finderQuery' => '',
  30. 'counterQuery' => ''
  31. ),
  32. 'FriendFrom' => array(
  33. 'className' => 'Friendship',
  34. 'foreignKey' => 'user_from'
  35. ),
  36. 'FriendTo' => array(
  37. 'className' => 'Friendship',
  38. 'foreignKey' => 'user_to'
  39. ),
  40. 'MessageFrom' => array(
  41. 'className' => 'Message',
  42. 'foreignKey' => 'user_from'
  43. ),
  44. 'MessageTo' => array(
  45. 'className' => 'Message',
  46. 'foreignKey' => 'user_to'
  47. )
  48. );
  49. var $hasAndBelongsToMany = array(
  50. 'UserFriendship' => array(
  51. 'className' => 'User',
  52. 'joinTable' => 'friendships',
  53. 'foreignKey' => 'user_from',
  54. 'associationForeignKey' => 'user_to'
  55. ),
  56. 'UserMessages' => array(
  57. 'className' => 'User',
  58. 'joinTable' => 'messages',
  59. 'foreignKey' => 'user_from',
  60. 'associationForeignKey' => 'user_to'
  61. ),
  62. 'Platform' => array(
  63. 'className' => 'Platform',
  64. 'joinTable' => 'platforms_users',
  65. 'foreignKey' => 'user_id',
  66. 'associationForeignKey' => 'platform_id',
  67. 'unique' => 'keepExisting',
  68. 'conditions' => '',
  69. 'fields' => '',
  70. 'order' => '',
  71. 'limit' => '',
  72. 'offset' => '',
  73. 'finderQuery' => '',
  74. 'deleteQuery' => '',
  75. 'insertQuery' => ''
  76. )
  77. );
  78.  
  79. public function beforeSave($options = array()) {
  80. if (isset($this->data[$this->alias]['password'])) {
  81. $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
  82. }
  83. return true;
  84. }
  85.  
  86. public function getFriends($idToFind) {
  87. $data = $this->FriendFrom->find('all', array(
  88. 'conditions' => array(
  89. 'OR' => array(
  90. array('user_to' => $idToFind),
  91. array('user_from' => $idToFind)
  92. )
  93. )
  94. )
  95. );
  96. $friendslist = array();
  97. foreach ($data as $i) {
  98. if ($i['FriendFrom']['user_from'] == $idToFind) {
  99. $friendslist[] = $i['UserTo'];
  100. } elseif ($i['FriendFrom']['user_to'] == $idToFind) {
  101. $friendslist[] = $i['UserFrom'];
  102. }
  103. }
  104.  
  105. //die(debug($friendslist));
  106. die(debug($data));
  107. }
  108.  
  109. public function getPlatforms($user_id){
  110. $this->unBindModel(array(
  111. 'hasMany' => array('FriendFrom', 'FriendTo', 'MessageFrom', 'MessageTo', 'UserGame'),
  112. 'hasAndBelongsToMany' => array('UserFriendship', 'UserMessages'),
  113. ));
  114. $platforms = $this->find('all', array(
  115. 'conditions'=>array(
  116. 'User.id'=>$user_id
  117. )
  118. ));
  119.  
  120. return $platforms;
  121. }
  122.  
  123. }


  1. class UserPlatform extends AppModel {
  2.  
  3. public $belongsTo = array(
  4. 'User' => array(
  5. 'className' => 'User',
  6. 'foreignKey' => 'user_id',
  7. 'conditions' => '',
  8. 'fields' => '',
  9. 'order' => ''
  10. )
  11. );
  12.  
  13. }

kleus
Cytat "Teraz mój problem polega na tym że chciałbym wylistować metoda find('list') wszystkie platformy które należą do użytkownika o id 1.

Więc na chłopski rozum zapytanie:
  1. SELECT platforms.name, platforms.id FROM platforms LEFT JOIN platforms_users ON platforms_users.platform_id=platforms.id WHERE platforms_users.user_id=1


Działa idealnie w phpmyadminie.
Tylko jak teraz to zrobić w cake?
Próbowałem już wszystkiego...

Między innymi:
Kontroler users
  1. $this->User->Platform->find('list', array('conditions', array('User.id'=>'1')));"


coż to zapytanie
  1. $this->User->Platform->find('list', array('conditions', array('User.id'=>'1')));"
napewno wywala blad bo zle sa conditions -> odsyłam do book

find
find(string $type = 'first', array $params = array())

Find is the multifunctional workhorse of all model data-retrieval functions. $type can be either 'all', 'first', 'count', 'list', 'neighbors' or 'threaded' or any custom finder you can define. Keep in mind that $type is case sensitive. Using an upper case character (for example All) will not produce the expected results.

$params is used to pass all parameters to the various finds, and has the following possible keys by default - all of which are optional:
  1. 'conditions' => array('Model.field' => $thisValue), //array of conditions
  2. 'recursive' => 1, //int
  3. 'fields' => array('Model.field1', 'DISTINCT Model.field2'), //array of field names
  4. 'order' => array('Model.created', 'Model.field3 DESC'), //string or array defining order
  5. 'group' => array('Model.field'), //fields to GROUP BY
  6. 'limit' => n, //int
  7. 'page' => n, //int
  8. 'offset' => n, //int
  9. 'callbacks' => true //other possible values are false, 'before', 'after'
  10. )


Dodatkowo proponuje w cotrollerze dbac o exeptions czyli zanim sprawdzisz platformy wzgledem usera sprawdz czy user istnieje

przyklad: UsersController
  1. public function userPlatforms($id = null){
  2. if($this->request->is('post')){
  3. $this->User->id = $id
  4. if(!$this->User->exists()){
  5. throw new NotFoundException('Invalid user');
  6. }
  7. $this->User->Platform('list', array(
  8. 'fields' => array('id', 'name'), // Pola do listy - jak nie zdeklarujsz to na 99% bedziesz miec tablica patrz nizej pod kodem funkcji
  9. 'conditions' => array(
  10. // w tym przypadku nie musisz dawac warunku 'User.id' => $id ponieważ jest on zdeklarowany 2 linice funkcji userPlatforms
  11. ),
  12. ));
  13. }
  14. }
  15. /*
  16. array(
  17. 'lp' => 'model.id'
  18. );
  19. */
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.