我有两个具有一对多关系(用户和位置)的表,每个用户有一个位置,但位置可以有多个用户。
在 users
表中有一列名为 location_id
与名为 id
在 locations
table。
locations.id->users.location\u id。
所以当我想得到所有 users
以及他们的 locations
,我使用以下代码:
//Select all the users.
$stmt = $pdo->prepare('SELECT *
FROM users
JOIN locations ON users.location_id = locations.id ');
$stmt->execute();
$values = $stmt->fetchAll();
//Loop through the users.
foreach($values as $val){
$userName = $val['name'];
//Get The location_id from users table.
$locationId = $val['location_id'];
//Select the location based on this location_id.
$st = $pdo->prepare('SELECT * from locations WHERE id = :zid');
$st->execute(array('zid' => $locationId));
$v = $st->fetch();
$location = $v['location'];
}
有没有更好的方法得到同样的结果?
1条答案
按热度按时间oo7oh9g91#
据我所知,这也会起同样的作用