假设我有两个实体User和Product与Doctrine的多对多关系相关.
我想知道为我的User实体处理$ user-> hasProduct($ product)方法的最佳方法,即返回true是关系存在,否则返回false.
我现在正在这样做:
public function hasProduct($id)
{
foreach($this->getProducts() as $product) {
if($product->getId() == $id) {
return true;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
但我不确定这是最好的方式,特别是如果循环中有很多关系.
如果有人有更好的东西,请告诉我:)
我正在使用Symfony 3.1和Doctrine 2.5.
我像往常一样设置了很多ToMany关系:
manyToMany:
placeServices:
targetEntity: Acme\MyBundle\Entity\PlaceService
joinTable:
name: place_place_service
joinColumns:
place_id:
referencedColumnName: id
inverseJoinColumns:
place_service_id:
referencedColumnName: id
Run Code Online (Sandbox Code Playgroud)
并向我的实体添加方法
protected $placeServices;
...
public function __construct()
{
$this->placeServices = new ArrayCollection();
}
...
/**
* @return ArrayCollection
*/
public function getPlaceServices(): ArrayCollection
{
return $this->placeServices;
}
/**
* @param PlaceServiceInterface $placeService
* @return PlaceInterface
*/
public function addPlaceService(PlaceServiceInterface $placeService): PlaceInterface
{
if(!$this->placeServices->contains($placeService)) {
$this->placeServices->add($placeService);
}
return $this;
}
/**
* @param PlaceServiceInterface $placeService
* @return PlaceInterface
*/
public function removePlaceService(PlaceServiceInterface …Run Code Online (Sandbox Code Playgroud) 我想获取一些事件,按这些标准排序和分页:
我可以处理打开的/传入的订单,但我无法先切断 < 20km,这是我的查询构建器的样子:
public function fetchByLocation($day, $time, $latitude, $longitude, $page = 1, $itemPerPage = 10)
{
if(!$page) {
$page = 1;
}
$qb = $this->createQueryBuilder('event')
->select('event', 'GEO_DISTANCE(:latitude, :longitude, event.latitude, event.longitude) AS distance')
->setParameter('latitude', $latitude)
->setParameter('longitude', $longitude)
->where('(event.day = :day AND event.start >= :time) OR event.day > :day')
->setParameter('day', $day)
->setParameter('time', $time)
->addOrderBy('event.day', 'asc')
->addOrderBy('event.start', 'asc');
$qb->setFirstResult(($page - 1) * $itemPerPage)
->setMaxResults($itemPerPage);
return $qb->getQuery()->getResult();
}
Run Code Online (Sandbox Code Playgroud)
这将首先提供打开的事件,任何想法在查询构建器中处理 < 20km …
我有一个具有多个选择的实体字段类型:
$builder
->add('products', 'entity', array(
'class' => 'Acme\MyBundle\Entity\Product',
'choices' => $this->getAvailableProducts(),
'multiple' => true,
))
;
Run Code Online (Sandbox Code Playgroud)
我想在这个字段上添加一个最小/最大约束,
use Symfony\Component\Validator\Constraints\Choice;
...
'constraints' => array(new Choice(array(
'min' => $min,
'max' => $max,
'multiple' => true,
'choices' => $this->getAvailableProducts()->toArray(),
))),
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,当绑定表单时,'products'字段的值绑定是一个doctrine ArrayCollection,如果没有给出数组,验证器会抛出异常."类型数组的预期参数,给定的对象"
这是否意味着我必须使用"选择"字段才能使用最小/最大约束?