我正在创建一个任务管理应用程序演示项目,只是为了掌握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
根据您的命名,我会怀疑从Project到Task的OneToMany关系,以及从Task到Project的ManyToOne关系。
正确映射后,可以在Twig中使用:
{{ project.tasks|length }}
获取项目中的任务数。您需要做的就是将项目实体传递给Twig,Symfony将处理其余的工作,包括加载所有关系。
这是做您想做的最好的方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句