【问题标题】:Transform big array (graph of objects) to the necessary smaller array将大数组(对象图)转换为必要的较小数组
【发布时间】:2015-11-10 17:45:11
【问题描述】:

我有一个实体 Follow 来处理用户实体实例之间的多对多关系。相关表的列如下所示:

关注(id, follower_id, followee_id)

当我执行以下查询时(为了获取特定用户的关注者):

       $em= $this->entityManager;

       $query = $em->createQuery(
            'SELECT f
            FROM MembersManagementBundle:Follow f               
            WHERE p.followee = :wee'
            )->setParameter('wee', 1);

       $n= $query->getResult();

它(通常)给我这样的结果:

array (size=4)
  0 => 
    object(Members\Bundle\ManagementBundle\Entity\Follow)[347]
        private 'follower' => 
             object(Members\Bundle\ManagementBundle\Entity\User)[283]
                 protected 'id' => int 2
                 .........
        private 'followee' => 
             object(Members\Bundle\ManagementBundle\Entity\User)[283]
                 protected 'id' => int 1
                 .........
  1 => 
    ..........

虽然我想要类似的东西:

array (size=4)
   0 => '2'
   1 => '3'
   .....

我尝试了SELECT f.follower_idSELECT f.follower.id,但它们给了我语法错误。

它需要比我更高级的 DQL 和查询构建器知识,我正在从您这里的常规指导中寻求。提前致谢。

进展:

我设法使结果数组更小:

array (size=4)
  0 => 
    array (size=1)
      'id' => int 2
  1 => 
    array (size=1)
      'id' => int 3
  2 => 
    array (size=1)
      'id' => int 4
  3 => 
    array (size=1)
      'id' => int 5

但不像我原来的问题中提到的那样。如何去除主数组里面的数组?

$query = $em->createQuery(
                'SELECT u.id
                FROM MembersManagementBundle:Follow p, MembersManagementBundle:User u            
                WHERE p.followed = :wee
                AND u.id= p.follower'
                )->setParameter('wee', 1);

【问题讨论】:

    标签: php sql symfony doctrine dql


    【解决方案1】:

    您可能想要 IDENTITY() DQL 函数,它是 2.4 中的新功能,不幸的是,它被隐藏在 documentation 中(查看该部分的最后一个条目)。

    所以您的 DQL 可能类似于:

    SELECT IDENTITY(f.follower) AS f1_id, IDENTITY(f.followee) AS f2_id FROM MembersManagementBundle:Follow f WHERE p.followee = :wee
    

    这样做的原因是因为 DQL 和 Doctrine 在设计上是 SQL 之上的抽象级别,因此它隐藏了您必须在 SQL 和关系数据库中执行的身份映射以支持对象。因此,在 SQL 中,您只需从连接表中选择 ID,在这里您必须告诉 Doctrine 您想要对象的 IDENTITY

    此外,由于此 DQL 不返回实体并且是部分查询 (documentation),因此您需要执行另一个后处理步骤来获取您的数组,例如:

    $arr = array_map(function($row) { return $row['f1_id']; }, $query->getResult());
    

    希望这会为您指明正确的方向!

    【讨论】:

    • 在此处添加注释-您的array_map 的回调可以替换为current,您应该得到相同的结果。 array_map('current', $result);
    • 感谢约翰的询问。除了类型(字符串而不是int)之外,它给出的结果与我在进度中提到的大致相同。它确实更短并且可能执行得更快(因为它不涉及查询第二个表)。但特别感谢 PHP 代码行(这两种方法都成功了)以及您的答案的编写方式。谢谢
    • @Artamiel,感谢您的评论。新概念:-)
    • @Artamiel 和@John,实际上,当我查阅 PHP 官方文档阅读有关 array_map 及其回调的内容时,我从你那里学到了很多东西
    猜你喜欢
    • 2013-04-05
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 2021-05-03
    • 2018-12-04
    • 2021-06-16
    相关资源
    最近更新 更多