Symfony2 中的自定义存储库 类

Custom Repository Classes in Symfony2

我正在创建一个任务管理应用程序演示项目,只是为了掌握 symfony2。至此我已经完成了CRUD操作。 这是我的默认控制器。我在这里调用 getNumberOfTasks()。

namespace TaskManagerBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use TaskManagerBundle\Entity\Projects;
use TaskManagerBundle\Form\ProjectType;



class DefaultController extends Controller
{
public function indexAction()
{
    $em = $this->getDoctrine()->getManager();

    $entities = $em->getRepository('TestBundle:Projects')
            ->findAll();

    $tasks = $em->getRepository('TestBundle:Projects')
            ->getNumberOfTasks();

    return $this->render('TestBundle:Default:index.html.twig', [
                'projects' => $entities,
                'tasks' => $tasks,
            ]
    );
}

这是我的 ProjectRepository,我在其中定义了 getNumberOfTasks 方法。

<?php

      namespace TaskManagerBundle\Entity\Repository;

     use Doctrine\ORM\EntityRepository;
     use TaskManagerBundle\Entity\Projects;
     use TaskManagerBundle\Entity\Tasks;

     /**
      * ProjectsRepository
       *
      * This class was generated by the Doctrine ORM. Add your own               custom
       * repository methods below.
       */
     class ProjectsRepository extends EntityRepository
     {
      public $id;
      public function getNumberOfTasks()
     {
       //$projects = new Projects();

      $query = $this->getEntityManager()
        ->createQuery(
                    'SELECT p FROM TestBundle:Tasks p WHERE p.projects = :project_id'
                )
        ->setParameter('project_id', $this->id )
        ->getResult();
    return count($query);
}

}

这是我的index.html.twig

   {% for project in projects %}
      <tr>
         <td>
        {% if project.completed == 0 %}
            {{ tasks }}
        {% else %}
            Completed
        {% endif %}
      </td>
      </tr>
    {% endfor %}

我正在尝试获取每个项目的任务数。我怎么做? 在 yii2 中我可以只做 $this->id 但在这里我做不到。

您根本不需要 "getNumberOfTasks" 方法。

你应该做的是在你的学说实体中指定关联。

您可以在这里阅读:

http://doctrine-orm.readthedocs.org/en/latest/reference/association-mapping.html

根据您的命名,我怀疑从项目到任务是一对多关系,从任务到项目是多对一关系。

正确映射后,您可以在 Twig 中使用:

{{ project.tasks|length }} 

获取项目中的任务数。您需要做的就是将项目实体传递给 Twig,Symfony 将处理其余部分,包括加载所有关系。

这是完成您想要做的事情的最佳方式。