为什么我的doctrine查询内连接返回多维数组?

时间:2012-02-25 08:25:12

标签: mysql zend-framework multidimensional-array doctrine resultset

我在Zend框架下使用Doctrine 1.2来运行我的数据库查询。我有两个表,我使用内部连接查询,如下所示:

$q = Doctrine_Query::create()
    ->from('My_Model_MaterialsFromDb g')
    ->innerJoin('t.My_Model_TeachingMaterials t');
    ->where('g.id= ?', $id)
$result = $q->fetchArray();

基本上,第一个表(materialsFromDb)包含我用于课程的所有教材的列表。第二个(教学材料)有材料本身的细节。

当我运行此查询时,结果总是如下:

Array
(
[0] => Array
    (
        [id] => 1
        [activityId] => 1
        [materialId] => 2
        [My_Model_Materials] => Array
            (
                [id] => 2
                [title] => My Groovy Material
                [materialType] => Worksheet
                [description] => This is my groovy material. It looks really cool.
                [filename] => Groovy Material.doc
                [uploaderId] => 1
                [uploadDate] => 2012-02-16
            )

    )
)

有什么方法可以运行一个学说查询来“扁平化”到一个数组?结果是这样的,因为两个表都有一个名为“id”的主键吗?将这个多维数组作为我的结果至少可以说是一种真正的痛苦。

1 个答案:

答案 0 :(得分:3)

根据Doctrine 1.2文档,这正是应该发生的事情。

Doctrine hydration removes all duplicated data. It also performs many other things such as:

Custom indexing of result set elements
Value casting and preparation
Value assignment listening
Makes multi-dimensional array out of the two-dimensional result set array, the number of dimensions is equal to the number of nested joins
Now consider the DQL equivalent of the SQL query we used:

// test.php

// ...


 $q = Doctrine_Query::create()
        ->select('u.id, u.username, p.phonenumber')
        ->from('User u')
        ->leftJoin('u.Phonenumbers p');

    $results = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY);

    print_r($results);
The structure of this hydrated array would look like:

$ php test.php
Array
(
    [0] => Array
        (
            [id] => 1
            [username] =>
            [Phonenumbers] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [phonenumber] => 123 123
                        )

                    [1] => Array
                        (
                            [id] => 2
                            [phonenumber] => 456 123
                        )

                    [2] => Array
                        (
                            [id] => 3
                            [phonenumber] => 123 777
                        )

                )

        )
    // ...
)

尝试...

$result = $q->execute(array(), Doctrine_Core::HYDRATE_NONE);

...或

$result = $q->execute(array(), Doctrine_Core::HYDRATE_SCALAR);

这个应该返回类似

的内容
$user = array(
    'u_username' => 'jwage',
    'u_password' => 'changeme',
    // ...
);