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?
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)));