我有两个实体Post和Comment。
结构:
: id标题身体
备注:idpost_id身体活跃的
class Post
{
/**
* @ORM'Column(name="id", type="integer")
* @ORM'Id
* @ORM'GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM'Column(name="title", type="string", length=255)
*/
private $title;
/**
* @ORM'Column(name="body", type="text")
*/
private $body;
/**
* @ORM'OneToMany(
* targetEntity="Comment",
* mappedBy="post"
* )
*/
private $comments;
class Comment
{
/**
* @ORM'Column(name="id", type="integer")
* @ORM'Id
* @ORM'GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM'Column(name="body", type="text")
*/
private $body;
/**
* @ORM'ManyToOne(
* targetEntity="Post",
* inversedBy="comments"
* )
* @ORM'JoinColumn(
* name="post_id",
* referencedColumnName="id"
* )
*/
private $post;
因此,当我想获得一个帖子的所有评论,我使用$post->getComments(),它的工作原理。我如何添加额外的Where子句到这个关系中,如果我想只获得与active = 1的帖子。我知道可以通过DQL或queryBuilder来实现但我想知道如何通过映射
我认为只检索活动评论的最干净的方法是在您的Post
实体的getComments
方法中使用Doctrine的Criteria
对象
use Doctrine'Common'Collections'Criteria;
和
public function getComments()
{
$criteria = Criteria::create();
$criteria->where(Criteria::expr()->eq('active', 1));
return $this->comments->matching($criteria);
}
编辑
如果您希望在每次检索活动注释时防止多次查询,则需要将它们存储在一个局部变量中。您可以添加$active_comments
和getActiveComments
,而不是修改getComments
,它们将填充$active_comments
,并且只有当$active_comments
是false
时才会查询数据库。
class Post {
private $active_comments;
public function getActiveComments()
{
if(!$this->active_comments) {
$criteria = Criteria::create();
$criteria->where(Criteria::expr()->eq('active', 1));
$this->active_comments = $this->comments->matching($criteria);
}
return $this->active_comments;
}