比方說,我有2個PHP對象:與連接表PDO FETCH_CLASS
<?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
謝謝!
UPDATE:
ATM我補我的「郵報」級這樣的:
$statement = $db -> prepare($query);
$statement -> execute();
$statement -> setFetchMode(PDO::FETCH_CLASS, 'Post');
$posts = $statement -> fetchAll();
那麼,如何將不得不改變,對於又充盈着其他類「用戶」?
SOLUTION:
$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;
你的問題幫了很多!謝謝! – 2017-01-28 09:38:09