Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple relations in CakePHP

I'm creating a tournament-platform with CakePHP. Currently I've created the following tables, models and controller which work perfectly: Tournaments, Users, and Teams.

I've created a "Tournamentuser" table, controller & model as well, where the tournament_id, user_id and team_id is stored.

Then when using View.ctp under Tournaments, it should display the User.Username & Team.Username in relation to the Tournamentuser. As of now, I have only managed to retrieve the id's from the table via. a foreach(.. as ..). I can see in the CakePHP query that it retrieves the data, I just don't know how to print it.

like image 628
2mas Avatar asked May 07 '26 01:05

2mas


1 Answers

I suppose you already know this but in CakePHP the conventions are:

  • models must have singular name: user/car/image
  • controllers must have plural name: users/cars/images
  • tables must have plural name: users/cars/images

If for example we need a relation: tournament-user we must follow the conventions(in CakePHP 2+):

  • controller: TournamentsUsersController.php
  • model: TournamentsUser.php
  • table: tournaments_users

If all the above conventions are followed before you can have your relation, tournaments-users you must define the relation between the two tables.

Here you can find more details on how to do this: http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html

If everything is done correctly until this point, you can now query the TournamentsUser Model.

Assuming you are in TournamentsUsersController.php controller:

$data = $this->TournamentsUser->find('all');

You can now see what $data contains using:

debug($data);

For printing the data you can use either a for/foreach loops:

$size = count($data);
for($i=0; $i<$size; ++i) {
   debug($data[$i]);
}
like image 181
Catalin MUNTEANU Avatar answered May 09 '26 06:05

Catalin MUNTEANU



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!