【问题标题】:Group By within contain cakephpGroup By 内包含 cakephp
【发布时间】:2020-12-18 11:53:00
【问题描述】:

你好,我想在 cakephp 中使用 group by。在以下情况下,我只想在 organizationUser 数组中采用不同的组织..

         $options = array(
        'conditions' => array('User.' .$this->User->primaryKey => $userId), 
        'contain' => array(
                        'OrganizationUser'=>array(
                            'conditions'=>['status'=>3],
                            'group'=> array( 'OrganizationUser.organization_id')),
                        'OrganizationUser.Organization',
                        'OrganizationUser.Organization.Noticeboard',
                        'OrganizationUser.Organization.Newsboard',
                        'OrganizationUser.Organization.Noticeboard.Branch',
                    ),
        'page'=>$page,
        'limit'=>$limit
        );



        $org = $this->User->find('all', $options);

但这会引发类似“未找到列”的错误,并且“条件”在 OrganizationUser 中工作正常,但“组”无法正常工作。我使用的是 cakephp 版本 2。提前致谢。

【问题讨论】:

    标签: php cakephp


    【解决方案1】:

    我不认为 cakephp 2+ 提供了像您所做的那样使包含中的字段不同的东西。所以最好尝试跟随.. 替换:

    'group'=> array( 'OrganizationUser.organization_id')
    

    'fields'=> array( 'DISTINCT OrganizationUser.organization_id')
    

    这可能对你有用。

    【讨论】:

    • 嗯,一个更好控制的替代方法是将joins 与查询生成器一起使用......我会发布一个新答案,但由于这个问题在 cake 3.0 中得到了解决,所以我没有认为它值得对这个聪明的解决方案发表评论。
    【解决方案2】:

    就我而言,我使用的是 cake 版本 4+。

    在我的表中我建立的关系

    $this->belongsTo('CreatedOperator')
          ->setClassName(USERS_PLUGIN . '.Users')
          ->setForeignKey('created_by')
          ->setJoinType('INNER')
       ;
    

    我将这种关系称为

           $query
            ->disableHydration()
            ->select([
                'CreatedOperator.id',
                'CreatedOperator.first_name',
                'CreatedOperator.last_name',
                'full_name' => $query->func()->concat(['CreatedOperator.first_name' => 'identifier',' ','CreatedOperator.last_name' => 'identifier']),
                'total' => $query->func()->count('CreatedOperator.id')])
            ->contain(['CreatedOperator'])
            ->group(['CreatedOperator.id'])
            ;
    
        return $query->toList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-26
      • 2014-12-26
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多