在CakePHP中管理双向关系而不两次检索数据

I am having troubling linking some of my models together. Users have one of three roles:

  • Student
  • Lecturer
  • Admin

Information that is shared between the 3 roles is stored in a User table. When a User wants to change their role they make a role request that must be accepted by Admin.

  • User has one Student
  • User has one Lecturer
  • User has one Admin
  • User has one RoleRequest
  • Student belongs to User
  • Lecturer belongs to User
  • Admin belongs to User

What I am struggling with is that I cannot find a way of retrieving the data of a user without retrieving their role or their user data twice. If I retrieve the User object with recursive set to 2 I get the user data twice as it is also inside the Lecturer object. If I do the same with the Lecturer object I get the lecturer data twice as it is also inside the User object.

If I understood your question correctly, I'm guessing you're not using Contaible.

With that behaviour, you can do something like

$this->User->find('all', array('contain'=>'Lecturer'));

and that will retrieve an array similar to

[User] => array(/*user data*/),
[Lecturer] => array(/*Lecturer data*/)

Just remember to define your models as containable.

Don't use recursive. Set public $recursive=-1; in your AppModel, then use CakePHP's AMAZING ContainableBehavior to retrieve whatever data you'd like.