Christopher Roy
Christopher Roy

Reputation: 306

CakePHP Pagination with HABTM relationship

I have a 'Club' HABTM 'Member' relationship.

From the ClubsController::View($id) view. I wish to show ALL the Members that belong to that ONE Club in a paginating table. I have tried many things but all were not exactly what I was looking for. The most common, seemingly related solution looked like CakePHP multi-HABTM associations with pagination but this would give me ALL the 'Club' that belong to ONE 'Member' from the ClubsController. As apposed to ALL the 'Member' from the ONE 'Club' from the ClubsController. I feel this should be an obvious task.

Upvotes: 0

Views: 244

Answers (2)

guillobuteler
guillobuteler

Reputation: 368

Im answering because I can't comment on Meibooms answer. It's wrong, because there shouldn't be a Member.club_id field as its a HABTM relation. Instead, what you should have is a join table: ClubsMembers.club_id ClubsMembers.member_id

As explained in the answer to the related question you mention, what you need to do is bind a fake hasOne relation to be able to set the conditions you want.

In your particular case:

        $this->Club->Member->bindModel(array(
            'hasOne' => array('ClubsMember')
        ), false);

        // Set up the paginate options array
        $this->paginate['Member'] = array(
            'contain' => array(
                'ClubsMember',
            ),
            'conditions' => array(
                'ClubsMember.club_id' => $club_id,
            ),
            //Group since the HasOne may return multiple rows for each
            //(if $club_id is an array of IDs and a Member is in more than one of those).
            'group' => 'Member.id',
            'order' => 'Member.name',
        );

        $this->set('members', $this->paginate('Member'));

Ignore the contain part if you don't use ContainableBehavior. (Cake will ignore it anyway.)

Upvotes: 2

M. Meiboom
M. Meiboom

Reputation: 164

It sounds to me like a simple paginate on Member with the conditions of 'Member.club_id' => $id should do the trick for you.

ps. What version of CakePHP are you using? Newer versions are a bit more sophisticated with pagination afaik.

Upvotes: 0

Related Questions