douji2283 2012-09-27 23:51
浏览 16
已采纳

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?

  • 写回答

2条回答 默认 最新

  • doujujian0052 2012-09-28 00:08
    关注

    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)));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗