假设我有 2 个 php 对象:
<?php
class Post {
public $id;
public $text;
public $user_id;
}
?>
和
<?php
class User {
public $id
public $name
}
?>
每个帖子都有一个唯一的约束,数据库中有 1 个用户。
我想使用适用于所有“发布”属性的 PDO“FETCH_CLASS”方法将数据填充到“发布”对象中,但是如何填充“用户”中的属性?
我的 SQL 语句如下所示:
SELECT post.id,
post.text,
post.user_id,
user.id,
user.name
FROM POST INNER JOIN User on post.user_id = user.id
谢谢!
更新:
ATM 我这样填写我的“邮政”类:
$statement = $db -> prepare($query);
$statement -> execute();
$statement -> setFetchMode(PDO::FETCH_CLASS, 'Post');
$posts = $statement -> fetchAll();
那么我将如何更改它以填充另一个类“用户”?
解决方案:
$statement = $db -> prepare($query);
$statement -> execute();
$posts = array();
while (($row = $statement->fetch(PDO::FETCH_ASSOC)) !== false) {
$post = new Post();
$post->id = $row['post_id'];
$post->text = $row['post_text'];
$post->created = $row['post_created'];
$post->image = $row['post_image'];
$post->url = $row['post_url'];
$post->weight = $row['post_weight'];
$post->likes = $row['post_likes'];
$user = new User();
$user->id = $row['user_id'];
$user->nickname = $row['user_nickname'];
$user->created= $row['user_created'];
$user->locked = $row['user_locked'];
$post->user = $user;
$posts[] = $post;
}
return $posts;