3
votes

I have the following relations:

  • User hasMany UserNotification
  • Notification hasMany UserNotification
  • UserNotification belongsTo User, Notification

  • notifications table has the following columns: id, subject, content

  • users_notifications table has the following columns: id, user_id, notification_id, status

In the UsersController, how can I retrieve all notifications from one user? (That means, for each notification all these details: subject, content and status).

And also, how can I limit the number of fields returned? As I am making the request from the UsersController, I don't want to retrieve any field from the User model in the find() array.

Thank you!

1

1 Answers

3
votes

In order to retrieve Notifications from the UsersController, simply do this:

$notifications = $this->User->Notification->find('all');

Basically, you can use the association to access the Notification model.

Next, in order to limit the fields, you can approach this in two ways. First would be to set the $recursive property to -1.

Use this line in the Notification model if you want it to happen everywhere throughout your application. Use it in the AppModel if you want it to happen for every model.

var $recursive = -1;

You could also place the following line before the aforementioned find() statement:

$this->User->Notification->recursive = -1;

The second way would be to use the Containable behavior.

Place the following line in your Notification model (or AppModel for global effect):

var $actsAs = array('Containable');

Now, by default, it wouldn't pull the User model. But if you ever wanted it to be pulled along with the Notification data, then your query should look like this:

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

Hope this helps!