2016-03-09 87 views
0

我怎样才能让这个例子发生?车库和红色汽车之间没有关系。车库和汽车之间只有关系。 我知道我可以使用这个存储库,但实际上我想要一个在车库里的吸气剂,它将只返回红色汽车。我认为DQL将成为awnser的一部分。主义实体自定义获取者

$myFavoriteCars = $myGarage->getRedCars(); 

Garage.php: 
--------------------------- 
@OneToMany(...Car...) 
private $cars 

public function getCars() 
{ 
    return $this->cars; 
} 

public function getRedCars() 
{ 
    // How to receive only the red cars? 
    // Some DQL in here? 
} 


Car.php: 
------------------------- 
@ManyToOne(...Garage...) 
private $garage 

private $color 

谢谢。 Richard

+0

你的实体中不应该有数据访问逻辑。它打破了关注点的分离,使测试变得更加困难,并且不利于可维护性。您的数据访问层和域层应该分开。这就是存储库的用途。 – peuh

回答

0

据我所知,这是不可能的。

我建议通过增加@ORM \实体线Garage.php来为你的车库实体特定的资源库:

/** 
* Garage 
* 
* @ORM\Table(name="garages") 
* @ORM\Entity(repositoryClass="AppBundle\Repository\GarageRepository") 
*/ 
class Garage 

然后在你的包创建一个新的文件夹,名为库和创建GarageRepository .php文件夹内。该文件可能看起来像下面的示例。

<?php  
namespace AppBundle\Repository; 


use Doctrine\ORM\EntityRepository; 

/** 
* Class GarageRepository 
* 
* @package AppBundle\Repository 
*/ 
class GarageRepository extends EntityRepository 
{ 
    /** 
    * finds one or more cars with a specific color 
    * 
    * @param string|int $color Could be a string like 'red' or and enumeration like Color::red which translate to an 
    *       integer or the id from a color if the colors are in the database. 
    * 
    * @return mixed 
    * @throws \Doctrine\ORM\NonUniqueResultException 
    */ 
    public function findCarsByColor($color) 
    { 
     return $this->createQueryBuilder('g') 
        ->where('g.color = :color') 
        ->setParameter('color', $color) 
        ->getQuery() 
        ->getOneOrNullResult(); 
    } 
} 

或者更短的解决方案可能会在您的控制器中添加$this->getDoctrine()->getRepository('AppBundle:Garage')->findBy(['color' => 'red']);。这样你就不必创建一个单独的资源库类,因为教义将使用默认的类。但是,在所有情况下,您都尝试通过原则访问数据,您需要某种存储库。

+0

我试图避免使用存储库。 AFAIK你的仓库将返回红色车库。我认为CarRepository :: getByGarageAndColor(车库,颜色)可以做到这一点。不幸的是,这不是我正在寻找的解决方案。 'indexBy'解决方案就是我要调查的内容。谢谢你的想法。 –

+0

更新我的答案与部分索引错误。无论如何,你为什么试图避免仓库?因为Doctrine是使用存储库模式构建的。 – lorenzobe