Order data based on count of related table data

こ雲淡風輕ζ 提交于 2019-12-24 15:09:12

问题


I have Two diff tables as given below:

users and posts

Need data from user's table order by count of posts table

Relationship is defined as:

User Model:

public $hasMany = array('Post');

Post Model

Public $belongsTo = array('User');

回答1:


counterCache - Cache your count()

This function helps you cache the count of related data. Instead of counting the records manually via find('count'), the model itself tracks any addition/deleting towards the associated $hasMany model and increases/decreases a dedicated integer field within the parent model table.

The name of the field consists of the singular model name followed by a underscore and the word “count”:

my_model_count

Let’s say you have a model called ImageComment and a model called Image, you would add a new INT-field to the image table and name it image_comment_count.

Once you have added the counter field you are good to go. Activate counter-cache in your association by adding a counterCache key and set the value to true:

<?php
class Image extends AppModel {
    public $belongsTo = array(
        'ImageAlbum' => array('counterCache' => true)
    );
}

From now on, every time you add or remove a Image associated to ImageAlbum, the number within image_count is adjusted automatically.

You can also specify counterScope. It allows you to specify a simple condition which tells the model when to update (or when not to, depending on how you look at it) the counter value.

Using our Image model example, we can specify it like so:

<?php
class Image extends AppModel {
    public $belongsTo = array(
        'ImageAlbum' => array(
            'counterCache' => true,
            'counterScope' => array('Image.active' => 1) // only count if "Image" is active = 1
    ));
}


来源:https://stackoverflow.com/questions/12297743/order-data-based-on-count-of-related-table-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!