如何让这个例子发生? Garage en red Cars之间没有任何关系。 Garage en Cars之间只有一种关系。 我知道我可以使用一个存储库,但实际上我想在车库中使用一个只能返回红色汽车的吸气剂。我假设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
谢谢。 理查德
答案 0 :(得分:0)
据我所知,这是不可能的。
我建议通过将@ORM \ Entity行添加到Garage.php来为您的Garage实体创建一个特定的存储库:
/**
* Garage
*
* @ORM\Table(name="garages")
* @ORM\Entity(repositoryClass="AppBundle\Repository\GarageRepository")
*/
class Garage
然后在捆绑包中创建一个名为Repository的新文件夹,并在该文件夹中创建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']);
。这样您就不必创建单独的存储库类,因为doctrine将使用默认的类。但在所有情况下,您都试图通过学说访问数据,而您需要某种存储库。