1
votes

I'm having trouble getting my head around my model associations in CakePHP. I've not worked with OOP or MVC before and I'm finding it a bit tricky.

Here is what I have:

Clubs

Users on the system are "Clubs". A club has various fields including a primary contact person - clubs.club_primary_contact_id

Teams

Clubs can have one or more teams associated with them. Like clubs, teams also have a primary contact person - teams.team_primary_contact_id. Teams also have a type and are linked to a types table - teams.type_id. Linked to clubs via teams.club_id

Contacts

Clubs can have one or more contacts associated with them. Linked to clubs via contacts.club_id

Types

types.id and types.type_name

I want to be able to access clubs/view/x and display a page showing the following:

  • Club primary contact name/email
  • All club contacts
  • All club teams including team primary contact name/email

The add/edit/delete functions for TeamsController works fine - i.e. I can call on the list of contacts & types and display those in a select box in the view form.

I'm having trouble accessing all of this neatly from the Club model though.

What are my associations here? Here is what I have in my model classes at present.

App/Model/Club.php

public $hasMany = array(
    'Team' => array(
        'className' => 'Team',
        'foreignKey' => 'club_id'
    ),
    'Contact' => array(
        'className' => 'Contact',
        'foreignKey' => 'club_id',
        'order' => 'contact_name DESC'
        )
);

public $belongsTo = array (
    'ClubPrimaryContact' => array(
        'className' => 'Contact'
    )
);

App/Model/Team.php

public $belongsTo = array (
    'TeamPrimaryContact' => array(
        'className' => 'Contact'
    ),
    'Club',
    'Type'
);

App/Model/Contact.php

public $hasManyAndBelongsTo = array(
    'Team' =>
        array(
            'className' => 'Team'
        )
);

App/Model/Type.php

public $belongsTo = array (
    'Team' => array(
        'className' => 'Team'
    )
);
1

1 Answers

0
votes

Sticking to the conventions will help a bit here.

If you want the club to belong to a contact - give it a contact_id and set a belongs_to relation in the club model to Contact. You will need to give that relation a different Alias to the Has_Many relation alias - so something like:

public $belongsTo = array(
        'Leader' => array(
            'className'    => 'Contact'
        )
    );

Likewise for Teams, define a belongs_to with a contact_id for the leader with an alias, and a regular has_many relation for contacts.

Then when querying - you will need to set recursive high enough to get all the results, or once you have that working, refine your queries with containable behaviour.

Then just query as per normal & use debug() to see the array structure returned