¿Pueden ayudarme con el código de consulta CakePHP ? Logré hacer código MySQL pero no puedo convertirlo a CakePHP

Aquí está el código MySQL

SELECT team_name, count(team_members.id)
FROM teams
LEFT JOIN team_members ON teams.id = team_members.team_id
WHERE teams.user_id = 15
GROUP BY teams.id

Y así es como intenté obtener el código de CakePHP :

$email = $this->request->getQuery('email');
        $user = $this->Users
            ->find('all')
            ->where(['email' => $email])->first();

        $options = array(
            'joins' =>
                array(
                    array(
                        'table' => 'TeamMembers',
                        'alias' => 'TeamMembers',
                        'type' => 'left',
                        'foreignKey' => false,
                        'conditions'=> array('TeamMembers.team_id = Teams.id')
                    ),
                ),
        );

        $teams = $this->Teams->find('all', $options)
            ->select(["team_name","id",'count_members' => 'count(*)'])
            ->where(['Teams.user_id' => $user->id])
            ->group(['Teams.id']);
0
modivno 16 oct. 2018 a las 18:19

2 respuestas

La mejor respuesta

Prueba esto:

    $teams = \Cake\ORM\TableRegistry::get('Teams');

    $query = $teams->find();

    $res = $query
            ->select([
                'team_name',
                'count' => $query->func()->count('team_members.id')
            ])
            ->join([
                'table' => 'team_members',
                'type' => 'LEFT',
                'conditions' => 'teams.id = team_members.team_id',
            ])
            ->group('teams.id');
0
tphobe9312 17 oct. 2018 a las 07:30
$teams=$this->Team->find('all',array(
                    'recursive'=>-1,
                    'conditions'=>array('Team.user_id = 15'),                                                                                
                    'joins'=>array(
                                array('table'=>'team_members',
                                      'alias'=>'TeamMember',
                                      'type'=>'left',
                                      'conditions'=>array(
                                           'Team.id = TeamMember.team_id',
                                       ),
                                    ),
                            ),
                    'fields'=>array(
                                'count(TeamMember.id) as total_team_members',
                                'Team.team_name'
                            ),
                    'group' =>array('Team.id ASC'),                                                     

                )                
        );
0
P.Banerjee 22 oct. 2018 a las 12:32