zend框架 - 可以从sql查询结果数组包含数据库名称吗?

时间:2018-01-08 19:07:30

标签: php mysql zend-framework2 zend-framework3

如果我们运行如下查询:

SELECT `user`.`user_id`
     , `user`.`username`
     , `profile`.`user_id`
     , `profile`.`name`
     , `profile`.`location`
  FROM `user`
  JOIN `profile`
 USING (`user_id`)
 WHERE `user`.`user_id` = 1;

然后我们得到结果集:

object(ArrayObject)
    private 'storage' => 
        array
           'user_id' => string '1'
           'username' => string 'ExampleUsername'
           'name' => string 'Example name'
           'location' => string 'Example location'

请注意user_id字段只返回一次,即使它在SQL查询中存在两次。

有没有办法将表名作为结果集的一部分返回?例如,需要以下结果集:

object(ArrayObject)
    private 'storage' => 
        array
           'user' => array
               'user_id' => string '1'
               'username' => string 'ExampleUsername'
           'profile' => array
               'user_id' => string '1'
               'name' => string 'Example name'
               'location' => string 'Example location'

我已经在其他框架(Laravel,CodeIgniter)中看到了这一点,但我没有看到Zend Framework版本2或3的选项。

这只是一个示例SQL查询。我们在项目中运行更复杂的查询,其中返回的关联数组(表名为键)将是理想的。

1 个答案:

答案 0 :(得分:1)

我认为您的意思是希望密钥包含表名,而不是数据库名称。

IIRC在Zend Framework中没有内置的方法可以做到这一点。

您可以使每个键区别开来,但是您可以通过定义列别名来完成此操作:

SELECT `user`.`user_id` AS user_user_id
     , `user`.`username`
     , `profile`.`user_id` AS profile_user_id
     , `profile`.`name`
     , `profile`.`location`
  FROM `user`
  JOIN `profile`
 USING (`user_id`)
 WHERE `user`.`user_id` = 1;

这是任何数据库库的常见问题,它返回结果的关联数组,而不仅仅是Zend Framework,甚至不是PHP。

您所展示的第二个示例,即将列提取到由表分解的某种嵌套数据结构中,在我曾经使用过的任何数据库中都不受支持。它将如何返回以下查询的结果?

SELECT user.user_views + profile.profile_views AS total_views
FROM user JOIN profile USING (user_id)

total_views密钥或user密钥会属于profile吗?

还有许多其他类似的SQL查询示例返回的结果并非严格属于"属于"到任何一个连接表。