user5009491
user5009491

Reputation:

Group By within contain cakephp

Hellow , I want to use group by within contain in cakephp. In the following case i want to take only distinct organization within organizationUser array..

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

But this is throwing error like 'Column not found', and 'conditions' is working fine within OrganizationUser but 'group' not working.I am using cakephp version 2.Thanks in advance.

Upvotes: 1

Views: 2868

Answers (2)

sh6210
sh6210

Reputation: 4530

In my case, I'm using cake version 4+.

In my table the relation I've made

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

and I'm calling the relation like

       $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();

Upvotes: 0

Manohar Khadka
Manohar Khadka

Reputation: 2195

I don't think cakephp 2+ offer something like you are doing to make field distinct within contain. So better to try following.. Replace :

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

By

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

that might work for you.

Upvotes: 2

Related Questions