我正在使用PDO内连接三个表:“Users”,“Teams”和中间表“teams_users”。 “teams_users”处理用户和团队之间的多对多关系。许多用户都可以加入团队。每个团队都可以拥有很多用户。
我们的想法是从用户拥有权限的“团队”表中获取团队ID的数组(在team_users表中)。
$ username被传递到函数中。
当回显$ query时,它看起来像这样:
SELECT teams_users.team_id FROM users INNER JOIN teams_users ON users.id = teams_users.user_id INNER JOIN teams ON teams.id = teams_users.user_id WHERE users.username = :username ORDER BY teams.id ASC
public function findTeamsByUsername($username = "") {
$query = "SELECT teams_users.team_id " .
"FROM users " .
"INNER JOIN teams_users " .
"ON users.id = teams_users.user_id " .
"INNER JOIN " . $this->table . " " .
"ON " . $this->table . ".id = teams_users.user_id " .
"WHERE users.username = :username " .
"ORDER BY teams.id ASC";
echo $query;
$stmt = $this->pdo->prepare($query);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$r = $stmt->execute();
// $stmt->debugDumpParams();
if (!$r) {
return null;
} else {
// $teamSet = $stmt->fetchAll(PDO::FETCH_ASSOC);
$teamSet = $stmt->fetchAll();
return $teamSet;
}
}
MySQL Workbench中的输出是: TEAM_ID 1 2
PHP中的输出是: 数组([0] =>数组([team_id] => 1 [0] => 1 )[1] =>数组([team_id] => 2 [0] => 2 ))
PHP中的输出是有意义的除了[0] => 1和[0] => 2来自哪里?我不明白的是粗体。选择不应该退回一列吗?
将返回简化为单个ID数组的加分点如下:[1,2]
答案 0 :(得分:1)
请尝试使用fetchAll(PDO::FETCH_COLUMN, 0)
。默认情况下,fetchAll()
会返回"混合"具有关联和数字索引的数组。