带连接表的PDO FETCH_CLASS

时间:2013-03-04 13:38:42

标签: php mysql join pdo

假设我有2个php对象:

<?php
class Post {
    public $id;
    public $text;
    public $user_id;
}
?>

<?php
class User {
    public $id
    public $name
}
?>

每个帖子都有一个唯一约束,数据库中有一个用户。

我想用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我这样填写我的“Post”类:

    $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;

5 个答案:

答案 0 :(得分:2)

据我所知,直接在PDO中没有支持。通常,如果您需要根据ORM的责任查询结果创建复杂的对象图。

如果您需要此功能,我建议您使用DoctrinePropel,而不是自己写一些内容。还有其他人可能体重较轻,但我没有经验。

修改

我想也许我误解了这个问题,因为我确信别人可能会这样。我认为真正的问题是如何访问连接的列,而不是如何从中创建对象。

在这种情况下,只需使用PDO::FETCH_ASSOCPDO::FETCH_NUMERICPDO::FETCH_BOTH这样的标准arry fethc方法即可为您提供所查询的所有列。

因此,如果您想将其转换为“对象图”,则必须手动执行,而不是使用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
   */
}

答案 1 :(得分:1)

并不是对OQ的回应,而是因为它一直在谷歌上弹出(是的,我知道它超过一年)。您会发现跳过循环并分别查询每个表的速度要快得多。


    SELECT post.id, 
           post.text, 
           post.user_id, 
    FROM POST INNER JOIN User on post.user_id = user.id
      $statement = $db -> prepare($query);
        $statement -> execute();
        $statement -> setFetchMode(PDO::FETCH_CLASS, 'Post');
        $posts = $statement -> fetchAll();

    SELECT user.id, 
           user.name 
    FROM POST INNER JOIN User on post.user_id = user.id
      $statement = $db -> prepare($query);
        $statement -> execute();
        $statement -> setFetchMode(PDO::FETCH_CLASS, 'User');
        $users = $statement -> fetchAll();
    

答案 2 :(得分:1)

您可以尝试使用__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);

答案 3 :(得分:0)

如果你使用多个表,也许可以使用PDO :: FETCH_NAMED。或者使用PDO :: ATTR_FETCH_TABLE_NAMES。

答案 4 :(得分:0)

我的解决方法:

function groupQueryJoinClasses(\PDOStatement $stmt, $joinInfo = [], $idProperty = 'id')
{
    $result = [];

    $records = $stmt->fetchAll();

    if ( !empty($joinInfo) ) {
        foreach ($records as $record) {
            if ( !isset($result[$record->$idProperty]) ) {
                $result[$record->$idProperty] = $record;
            }
            foreach ($joinInfo as $target => $classInfo) {
                $vars = get_object_vars($record);
                $class = new $classInfo['class']();
                foreach ($vars as $key => $value) {
                    $keyData = explode('.', $key);
                    if ( $keyData[0] == $classInfo['prefix']) {
                        $class->$keyData[1] = $value;
                        unset($result[$record->$idProperty]->$key);
                    }
                }
                if ( !is_array( $result[$record->$idProperty]->$target) ) {
                    $result[$record->$idProperty]->$target = [];
                }
                $targetArray = &$result[$record->$idProperty]->$target;
                $targetArray[] = $class;
            }
        }
    } else {
        $result = $records;
    }

    return $result;
}

function getModel($query, $data, $entryClass, $joinInfo, $idProperty = 'id') {
    $pdo = new PDO(...);
    $stmt = $pdo->prepare($query);
    $stmt->execute($data);

    $stmt->setFetchMode(\PDO::FETCH_CLASS, $entryClass);

    return groupQueryJoinClasses($stmt, $joinInfo , $idProperty);
}

// Sample request

$query =
    'SELECT
        u.id as "id",
        p.id as "Post.id",
        p.name as "Post.name"
    FROM `user` u
    LEFT JOIN `posts` p ON p.user_id = u.id
    where id = :id'
;
$data = [ ':id' => 1 ];

$joinInfo = [
    'posts' => [
        'class' => Post::class,
        'prefix'=> 'Post'
    ]
];
$flowRules = getModel($query, $data, User::class, $joinInfo);

也许对任何人都很有趣,或者也许有人会以这种方式看到问题