2mas
2mas

Reputation: 127

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.

Upvotes: 3

Views: 177

Answers (2)

Catalin MUNTEANU
Catalin MUNTEANU

Reputation: 5634

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]);
}

Upvotes: 1

Dave
Dave

Reputation: 29121

If you're getting the data, but just need to access the values, you can use normal PHP array functionality:

echo $myData['User']['username'];
echo $myData['Team']['username'];

Or, if you have more than one:

foreach($myData as $data) {
    echo $data['User']['username'];
    echo $data['Team']['username'];
}

Obviously this will need to be tweaked per your code, but it should help you get the idea.

Upvotes: 0

Related Questions