Select only certain fields from associated models in CakePHP
I have the following relations:
User
hasManyUserNotification
Notification
hasManyUserNotification
UserNotification
belongsToUser
,开发者_如何学CNotification
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!
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!
精彩评论