一点背景知识:
现在我正在尝试构建一个查询:“获取属于我办公室的所有文章,或者拥有与我办公室共享的标签”。
我在 MySQL 中尝试了此操作,以下查询按预期工作:
SELECT
*
FROM
`articles` `a`
WHERE
(
`office_id` = 2
OR
`a`.`id` IN (
SELECT
`at`.`article_id`
FROM
`article_tags` `at`
WHERE
`at`.`article_id` = `a`.`id`
AND
`at`.`tag_id` IN
(
SELECT
`st`.`tag_id`
FROM
`shared_tags` `st`
WHERE
`st`.`shared_with_id` = 2
AND
`st`.`article` = 1
)
)
)
AND
`status` = 1
我的实体如下:
/**
* @ORM\ManyToMany(targetEntity="Tag", inversedBy="articles")
* @ORM\JoinTable(name="article_tags")
* @var ArrayCollection|Tag[]
*/
protected $tags;
/**
* @ORM\ManyToMany(targetEntity="Article", mappedBy="tags")
* @var ArrayCollection|Article[]
*/
protected $articles;
class SharedTag extends Entity
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
* @var int
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="Office", inversedBy="sharedTags")
* @ORM\JoinColumn(name="shared_with_id", referencedColumnName="id")
* @var Office
*/
protected $sharedWith;
/**
* @ORM\ManyToOne(targetEntity="Office", inversedBy="sharedTags")
* @ORM\JoinColumn(name="shared_by_id", referencedColumnName="id")
* @var Office
*/
protected $sharedBy;
/**
* @ORM\ManyToOne(targetEntity="Tag", inversedBy="sharedTags")
* @var Tag
*/
protected $tag;
/**
* @ORM\Column(type="boolean", options={"default" = 0})
* @var bool
*/
protected $template = 0;
/**
* @ORM\Column(type="boolean", options={"default" = 0})
* @var bool
*/
protected $article = 0;
/**
* @ORM\Embedded(class = "\ValueObjects\CreatedAt", columnPrefix=false)
* @var CreatedAt
*/
protected $createdAt;
}
那么,我如何在DQL或QueryBuilder中查询?我尝试了几种方法,但似乎无法在WHERE IN()查询中使用关系tag_id
中的articles.tags
。
提前谢谢!
经过一些试验和错误,感谢Jean的回答,我能够像这样查询:
SELECT
a
FROM
Article a
LEFT JOIN a.tags t
LEFT JOIN a.office o
LEFT JOIN o.sharedTags st
WHERE
(
a.office = :office
OR
(
t = st.tag
AND
st.sharedWith = :office
AND
st.article = 1
)
)
AND
a.status.status = :status
AND
a.template IS NULL
GROUP BY a.id
答案 0 :(得分:0)
您应该使用连接而不是子查询。这样,您可以获得更好的性能和更简单的DQL代码:
SELECT DISTINCT `a`
FROM `articles` `a`
LEFT JOIN `a.tags` `t`
LEFT JOIN `t.shared_with_id` `o`
WHERE (`a`.`office_id` = 2 OR `o`.`id` = 2)
AND `status` = 1