1

我在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”的主键?作为我的结果拥有这个多维数组是我们至少可以说的一个真正的痛苦。

回答

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', 
    // ... 
); 
+0

非常有帮助。谢谢! – blainarmstrong 2012-02-25 12:11:26