我怎样才能实现这个例子?没有关系 车库 en 红色汽车.只有关系 车库 en 汽车.我知道我可以为此使用存储库,但实际上我想要车库中的 getter,它只会返回红色汽车。我认为DQL将成为遮阳篷的一部分。
$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
谢谢。理查
据我所知,这是不可能的。
我建议通过将@ORM''实体行添加到车库来为您的车库实体创建一个特定的存储库.php:
/**
* 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 将使用默认的存储库类。但是在所有情况下,您都尝试通过原则访问数据,您将需要某种存储库。