Rap*_*ger 10 php mysql pdo join
假设我有2个php对象:
<?php
class Post {
public $id;
public $text;
public $user_id;
}
?>
Run Code Online (Sandbox Code Playgroud)
和
<?php
class User {
public $id
public $name
}
?>
Run Code Online (Sandbox Code Playgroud)
每个帖子都有一个唯一约束,数据库中有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
Run Code Online (Sandbox Code Playgroud)
谢谢!
更新:
ATM我填写我的"Post"类,如下所示:
$statement = $db -> prepare($query);
$statement -> execute();
$statement -> setFetchMode(PDO::FETCH_CLASS, 'Post');
$posts = $statement -> fetchAll();
Run Code Online (Sandbox Code Playgroud)
那么我如何更改它以填充其他类"用户"?
解:
$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;
Run Code Online (Sandbox Code Playgroud)
据我所知,PDO 中不直接支持。通常,如果您需要根据查询结果创建复杂的对象图,这就是 ORM 的职责。
如果您需要此功能,我建议您使用Doctrine或Propel,而不是自己编写一些东西。还有其他可能重量较轻的产品,但我没有使用它们的经验。
编辑:
我想也许我误解了这个问题,我确信其他人也可能误解了这个问题。我认为真正的问题是如何访问连接的列,而不是如何从它们创建对象。
在这种情况下,只需使用标准的 arry fethc 方法,例如PDO::FETCH_ASSOC, PDO::FETCH_NUMERICorPDO::FETCH_BOTH就会为您提供您查询的所有列。
因此,如果您想将其转换为“对象图”,您必须手动完成,而不是使用PDO::FETCH_CLASS.
例如:
//$db is pdo:
// also notice im aliase the columns prefixing the name so that we can tell what belongs to
// post and what belongs to user, an alternative approach would be to use FETCH_NUMERIC,
// which just uses the column positions from the seelct statement as the keys
// so in this case post.id would be in the array as key 0, and user.name would be in the
// array as key 4
$stmt = $db->prepare('SELECT post.id as p_id,
post.text as p_text,
post.user_id as p_user_id,
user.id as u_id,
user.name as u_name
FROM POST INNER JOIN User on post.user_id = user.id');
$stmt->execute();
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) {
print_r($row);
/* will output:
Array (
'p_id' => 'value'
'p_text' => 'value'
'p_user_id' => 'value'
'u_id' => 'value',
'u_name' => 'value'
)
So now you need to decide how to create your objects with the information returned
*/
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10678 次 |
| 最近记录: |