我有一个带有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
我缺少什么?我非常绝望:(
编辑: 刚刚发现,它只返回有回复的帖子。如何选择所有帖子,如果有回复,也会回复?
答案 0 :(得分: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时,它会尝试将帖子加入到回复中,如果帖子没有任何内容,结果将为空!