我在 SF2.0.15 和 Doctrine2 下,我有两个实体。
-远征-步骤
解释一下,一个探险可以有几个步骤,一个步骤可以属于几个探险。此外,一个探险属于他的创始人(名为“所有者”并存储在用户实体中)。因此,我选择在 Expedition 和 Steps 表之间进行 ManyToMany 连接。在您看来,这是一个好的选择还是一个错误的选择?
我想创建一个方法来选择属于一个探险队的所有步骤(我有探险队的 ID,它包含在 $id_exp 中)。所以,我在互联网上阅读了很多主题,但总是失败,我想知道为什么......
实体 Expedition.php
/**
* @ORM\ManyToOne(targetEntity="Easymuth\UserBundle\Entity\User")
* @ORM\JoinColumn(nullable=false)
*/
private $owner;
/**
* @ORM\ManyToMany(targetEntity="Easymuth\ExpeditionBundle\Entity\Step", cascade={"persist"})
*/
private $steps;
/**
* Add steps
*
* @param Easymuth\ExpeditionBundle\Entity\Step $steps
*/
public function addStep(\Easymuth\ExpeditionBundle\Entity\Step $step)
{
$this->steps[] = $step;
}
public function __construct()
{
$this->steps = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get steps
*
* @return Doctrine\Common\Collections\Collection
*/
public function getSteps()
{
return $this->steps;
}
ExpeditionRepository.php:
namespace Easymuth\ExpeditionBundle\Entity;
use Doctrine\ORM\EntityRepository;
class ExpeditionRepository extends EntityRepository
{
public function getStepsFromExpedition($id_exp) {
$qb = $this->createQueryBuilder('e')
->leftJoin('e.steps', 's')
->addSelect('s')
->where('e.id = :id')
->setParameter('id', $id_exp);
return $qb->getQuery()->getResult();
}
}
最后在我的控制器中,我有:
namespace Easymuth\ExpeditionBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Easymuth\ExpeditionBundle\Entity\Expedition;
class MainController extends Controller
{
public function stepsAction($id_exp) {
$expedition = $this->getDoctrine()
->getEntityManager()
->getRepository('EasymuthExpeditionBundle:Expedition')
->getStepsFromExpedition($id_exp);
print_r($expedition->getSteps()); // it displays a very long contents........
//return $this->render('EasymuthExpeditionBundle:Main:steps.html.twig'));
}
}
print_r(或 var_dump)上显示的错误是:
Fatal error: Call to a member function getSteps() on a non-object in /Applications/MAMP/htdocs/easymuth/src/Easymuth/ExpeditionBundle/Controller/MainController.php
非常感谢您的帮助 !