代码之家  ›  专栏  ›  技术社区  ›  Leo Galleguillos

zend framework-sql查询的结果数组是否可以包含数据库名称?

  •  1
  • Leo Galleguillos  · 技术社区  · 7 年前

    如果我们运行以下查询:

    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 回复  |  直到 7 年前
        1
  •  1
  •   Bill Karwin    7 年前

    我想你的意思是你希望钥匙包括 表名称 ,而不是数据库名称。

    IIRC在Zend框架中没有实现这一点的内置方法。

    您可以使每个键都不同,但这取决于您如何定义列别名:

    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查询示例,它们返回的结果并不严格“属于”任何一个联接表。