请帮助我使用 CakePHP 查询代码。我设法制作了 MySQL 代码,但无法将其转换为 CakePHP
这是 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
这是我尝试从 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 :(得分:0)
尝试一下:
$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');
答案 1 :(得分:0)
$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'),
)
);