一起获取一对多相关表,pdo

问题描述 投票:0回答:1

我具有PDO设置,并且可以正常工作。我可以addeditdel等。因此问题出在这里。 DB中有one to many关系,当我获取父表时,我希望它与相关的子表有关。

与PDO的数据库连接

private $server = "localhost";
private $username = "name";
private $password = "password";
private $database = "database_name";

protected function connect(){

    $dns = "mysql:host=" . $this->server . ";dbname=" . $this->database;
    $pdo = new PDO($dns, $this->username, $this->password);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

    return $pdo;
}

用户类

class Users extends Dbc {

    public function get_users(){

        $sql = "SELECT id, user from users";

        $stmt = $this->connect()->prepare($sql);
        $stmt->execute();
        $results = $stmt->fetchAll();

        $users = [];
        foreach ($results as $key => $value) {
            $users[] = $value;
        }

        echo json_encode($users);

    }   

}

这当然只返回users表,因此,正确的方法是在其中获取带有子表的用户表。我需要在PDO中进行哪些更改...

php pdo
1个回答
0
投票

PDO中没有任何更改。您只需要更改SQL及其处理方式即可。我在fetching one to many with PDO上的文章中对此进行了解释,但总之,您需要编写一个查询,该查询使用JOIN从子表中获取记录,然后在获取循环中添加条件以避免在结果数组中重复。

该示例摘自我的文章,因为您未提供有关表的任何详细信息:

$sql = "SELECT c.id as c_id, c.name as c_name, c.url, 
               p.id as p_id, p.name as p_name, p.price
        FROM category c
        JOIN product p ON p.category_id=c.id
        ORDER BY c.name, p.name
        LIMIT ?,?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$start, $limit]);

$data = [];
while ($row = $stmt->fetch()) {
    $product = [
        'id' => $row['p_id'],
        'name' => $row['p_name'],
        'price' => $row['price'],
    ];
    if (!isset($data[$row['c_id']])) {
        $row['c_id'] = [
            'name' => $row['c_name'],
            'url' => $row['url'],
            'products' => [$product]
        ];
    } else {
        $row['c_id']['products'][] = $product;[
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.