1

我有一个带有 yml 映射的实体“BlogPosts”:

type: entity
table: blog_posts
id:
  id:
    type: integer
    generator: { strategy: AUTO }
fields:
  body:
    type: text
  created_at:
    type: datetime
manyToMany:
  replies:
    targetEntity: BlogPosts
    inversedBy: replyTo
    orderBy: {"id": "DESC"}
    orphanRemoval: true
    joinTable:
      name: blog_post_replies
      joinColumns:
        reply_to_id:
          referencedColumnName: id
      inverseJoinColumns:
        reply_id:
          referencedColumnName: id
  replyTo:
    targetEntity: BlogPosts
    mappedBy: replies
manyToOne:
  user:
    targetEntity: User
    inversedBy: posts
    joinColumns:
      user_id:
        referencedColumnName: id
        nullable: false

问题是,当我尝试使用 JOIN 获取数据时,结果为空。

    $query = $em->createQuery("SELECT p, rl FROM <Bundle>:BlogPosts p JOIN p.replies rl WHERE p.user = 1");
    $posts = $query->getResult(); // Returns empty array

但它在没有连接的情况下完美运行:

    $query = $em->createQuery("SELECT p FROM <Bundle>:BlogPosts p WHERE p.user = 1");
    $posts = $query->getResult(); // Works as intended

我错过了什么?我真的很绝望:(

编辑:刚刚发现,它只返回有回复的帖子。我如何选择所有帖子,如果有回复,也回复?

4

1 回答 1

1

所以我发现了问题!而不是 JOIN 我使用了 LEFT JOIN:

$query = $em->createQuery("SELECT p, rl FROM <Bundle>:BlogPosts p LEFT JOIN p.replies rl WHERE p.user = 1");
$posts = $query->getResult(); // Now it works like a charm!

所以现在 MySQL 将结果加入到博客文章中!使用简单的 JOIN 时,它会尝试将帖子加入回复中,如果帖子没有,则结果将为空!

于 2012-09-21T07:42:11.757 回答