Search code examples
cakephpvirtualfieldpagination

CakePHP paginate 'virtual' field


I have a model Item with its corresponding table items and fields (field1, field2, etc).

I have another model, Comment, whith also its table and fields. One of the fields is item_rating, where users enter a number between 0 to 10 to rate the item.

Both models are related like Item hasMany Comment, and Comment belongsTo Item.

When paginating the Item model in the view, I would like to add the field item_rating along with its own fields, so users can see an average rating of the item and be able to sort by item_rating, apart from all the other fields that belong directly to Item.

To do this, I figure I would need 2 things:

  • Be able to create the item_rating field on the fly with the average of all its ratings
  • Be able to add that field to the pagination so users can see it and sort by it

Is this possible? Can anyone point me to the right direction of how to accomplish it? Or should I just add a real item_rating field to my items table and update the average everytime a new rating is added by a user?

Thanks so much in advance!


Solution

  • For me the best way is to use a real field in your parent table. Here is a behavior which you can use for your purpose:Aggregatable behaviour

    Edit:

    You can do such functionality by your own. Just create a field in your parent table which will hold the average rating. Then on afterSave() in your Rating model, add functionality that fills that field in the parent table with the average value.