0

My question is in relation this this answer. https://stackoverflow.com/a/8773953/1297775

I have read at many places, what @deceze put as: "To be quite honest, for any halfway complex application, relying on Cake's automagic handling of HABTM relationships can get quite fragile and hard to debug, so I always manage HABTM records myself."

Even the CakePHP book hints at it http://book.cakephp.org/2.0/en/models/saving-your-data.html#what-to-do-when-habtm-becomes-complicated

I want to ask, that when he says he 'manages' this HABTM records himself, does he...

1) Not create the HABTM relations in the models at all and create a model for the join table

OR

2) Create the HABTM relations in the models, but does not use it in the controller code by just using $this->FirstModel->JoinModel->saveAll($someData);

Thanks

Community
  • 1
  • 1
Gurpreet Singh
  • 153
  • 1
  • 3
  • 14

1 Answers1

2

Basically you need use a hasManyThrough relationship, which is essentially a HABTM setup manually which allows you to add extra data to the relationship (such as created/expiry dates). It's quite simple, you just need to create a model to join them and use the normal belongsTo and hasMany properties in the model, here is a simple user/membership/course setup:

class User extends AppModel {
    public $hasMany = array('Membership');
}

class Course extends AppModel {
    public $hasMany = array('Membership');
}

class Membership extends AppModel {
    public $belongsTo = array('User', 'Course');
}

The only fields (at minimum) the memberships table needs is course_id and user_id.

You can now operate on the Membership model as a normal model, without Cake treating it as HABTM and using its auto-magic whenever you save records. You can also use cool counterCaches on the membership model to count how many users a course has etc.

Dunhamzzz
  • 14,682
  • 4
  • 50
  • 74