假设我有 2 个 php 对象:
<?php
class Post {
public $id;
public $text;
public $user_id;
}
?>
和
<?php
class User {
public $id
public $name
}
?>
每个帖子都有一个唯一的约束,数据库中有 1 个用户。
我想使用 PDO 的“FETCH_CLASS”方法将数据填充到“Post”对象中,该方法适用于所有“Post”属性,但是如何填充“User”中的属性?
我的 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;
最佳答案
你可以试试像这样使用__set方法:
<?php
include 'connection.php';
class Post {
public $id;
public $text;
public $user;
public function __construct() {
$this->user = new User();
}
public function __set($name, $value) {
if (array_key_exists($name, get_object_vars($this->user))) {
$this->user->$name = $value;
} else {
$this->$name = $value;
}
}
}
class User {
public $id;
public $name;
}
$statement = $pdo->prepare("SELECT * FROM post "
. "LEFT JOIN user "
. "ON post.user_id = post.id");
$statement->execute();
$result = $statement->fetchAll(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, Post::class);
echo "<pre>";
var_dump($result);
关于php - 具有连接表的 PDO FETCH_CLASS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15202864/