Last x blog entries - but only once per user

前端 未结 4 1333
攒了一身酷
攒了一身酷 2020-12-18 13:59

I would like to display a box with the last x (say 5) blog entries. But I would like to avoid that a very active user is listed twice.

My tryout boils down to:

4条回答
  •  情话喂你
    2020-12-18 14:22

    Using a subquery seems to work - with this little trick:

    $options = array(
        'fields' => array('MAX(SubBlog.created)'),
        'conditions' => array('SubBlog.user_id = Blog.user_id')
    );
    $subquery = $this->subquery('all', $options);
    
    $options = array(
        'order'=>array($this->alias.'.published' => 'DESC'),
        'conditions' => array(
            'User.active' => 1,
            'Blog.status' => self::STATUS_ACTIVE, 
            'Blog.published = ' . $subquery
        ),
        'contain' => array('User.username'),
        'fields' => array(
            'User.id',  'User.username', 
            'Blog.id', 'Blog.headline', 'Blog.published'
        ),
        'limit' => $limit,
    );
    return $this->find('all', $options);
    

    subquery() is an AppModel method: https://github.com/dereuromark/tools/blob/2.0/Lib/MyModel.php#L405

提交回复
热议问题