Symfony 2 获得实体原则

标签 symfony doctrine-orm entity

我有两个类

    class Topic
    {
        protected $id;
        //....
    }

class Post
{
    protected $topic_id;
    //...
}

我想在 Topic 类中添加方法 getPostCount() 。在其他框架中我曾经使用类似的东西:

 public function getPostCount()
    {        
            $count = Post::find()
                ->where(['topic_id' => $this->id])
                ->count();

        return $count;
    }

但在 symfony2 中我不知道如何制作它。

最佳答案

您可以创建 repository class用这个方法。将存储库类名称添加到实体的映射定义中,如下所示:

/**
*  @ORM\Entity(repositoryClass="AppBundle\Repository\PostRepository")
*/
class Post
{
    protected $topic_id;
    //...
}

在你的存储库类中:

public function getPostCount($id)
{        
     $query = $this->createQueryBuilder('p')
        ->select('count(p.topic_id)')
        ->where('p.topic_id = :id')
        ->setParameter('id', $id)
        ->getQuery()->getSingleScalarResult();
    return $query; 
}

关于Symfony 2 获得实体原则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41961345/

相关文章:

java - (解决方法)在实体上使用@ConditionalOnProperty

jquery - Symfony2 功能测试 - 通过 jQuery 交互单击元素

symfony - 在 Symfony 表单类型中设置复选框错误消息

symfony - "association refers to the inverse side field"& "mappings are inconsistent with each other"

java - 对实体对象 spring/JPA/Java 进行验证的缺点

Java实体插入DB更改列类型

php - Symfony2 和 Vim 推荐

symfony - 使用 SonataAdminBundle 对实体进行自定义删除处理

php - 如何使用 Doctrine 在死锁后重试事务?

symfony - 为什么我的 Doctrine 自定义存储库认为我的实体是分离的?