CakePHP:选择拥有1个或更多帖子的用户

I have two tables: users and posts. I'm trying to select any users that have at least one post.

I'm guessing this require either a join or a subselect. Is there something in CakePHP that makes this simple?

Use counter caching, see http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#belongsto

counterCache: If set to true the associated Model will automatically increase or decrease the “[singular_model_name]_count” field in the foreign table whenever you do a save() or delete(). If it’s a string then it’s the field name to use. The value in the counter field represents the number of related rows. You can also specify multiple counter caches by using an array where the key is field name and value is the conditions. E.g.:

array( 'recipes_count' => true, 'recipes_published' => array('Recipe.published' => 1) ) counterScope: Optional conditions array to use for updating counter cache field.

No additional query needed in this case. It will automatically in- and decrease the count in the users table if you add/delete posts.

Example:

public $belongsTo = array(
    'User' => array(
        'foreignKey' => 'user_id',
        'counterCache' => true,
        'counterScope' => array(
            'published' => 1)));

This should select all users that made 1 post or more

SELECT * FROM `users` as u
INNER JOIN `posts` as p ON p.user_id = u.id

In cake you should be able to do something like this:

$this->User->find('all', array('joins' =>
    array(
        'table' => 'posts',
        'alias' => 'p',
        'type' => 'inner',
        'conditions' => array(
            'User.id = p.user_id'
        )
    )
);

[EDIT]

Maybe you could add

'group' => 'User.id'

or

'fields' => 'DISTINCT User.id, ...'

To remove duplicates entries