Подтвердить что ты не робот

Doctrine findBy 'не равно'

Как мне сделать

WHERE id != 1

В Доктрине?

У меня это до сих пор

$this->getDoctrine()->getRepository('MyBundle:Image')->findById(1);

Но как мне сделать "не равно"?

Это может быть глупо, но я не могу найти никакой ссылки на это?

Спасибо

4b9b3361

Ответ 1

Нет встроенного метода, который позволяет делать то, что вы намереваетесь сделать.

Вам нужно добавить метод в ваш репозиторий, например:

public function getWhatYouWant()
{
    $qb = $this->createQueryBuilder('u');
    $qb->where('u.id != :identifier')
       ->setParameter('identifier', 1);

    return $qb->getQuery()
          ->getResult();
}

Надеюсь, что это поможет.

Ответ 2

В настоящее время для этого существует подход, использующий критерии доктрины.

Полный пример можно увидеть в Как использовать метод findBy со сравнительными критериями, но краткий ответ приведен ниже.

use \Doctrine\Common\Collections\Criteria;

// Add a not equals parameter to your criteria
$criteria = new Criteria();
$criteria->where(Criteria::expr()->neq('prize', 200));

// Find all from the repository matching your criteria
$result = $entityRepository->matching($criteria);

Ответ 3

Чтобы немного повысить гибкость, я добавлю следующую функцию в свой репозиторий:

public function findByNot($field, $value)
{
    $qb = $this->createQueryBuilder('a');
    $qb->where($qb->expr()->not($qb->expr()->eq('a.'.$field, '?1')));
    $qb->setParameter(1, $value);

    return $qb->getQuery()
        ->getResult();
}

Тогда я мог бы назвать это в моем контроллере следующим образом:

$this->getDoctrine()->getRepository('MyBundle:Image')->findByNot('id', 1);

Ответ 4

Основываясь на ответе Луиса, вы можете сделать что-то более похожее на метод findBy по умолчанию.

Сначала создайте класс репозитория по умолчанию, который будет использоваться всеми вашими сущностями.

/* $config is the entity manager configuration object. */
$config->setDefaultRepositoryClassName( 'MyCompany\Repository' );

Или вы можете изменить это в config.yml

доктрина:   ORM:       default_repository_class: MyCompany\Repository

Тогда:

<?php

namespace MyCompany;

use Doctrine\ORM\EntityRepository;

class Repository extends EntityRepository {

    public function findByNot( array $criteria, array $orderBy = null, $limit = null, $offset = null )
    {
        $qb = $this->getEntityManager()->createQueryBuilder();
        $expr = $this->getEntityManager()->getExpressionBuilder();

        $qb->select( 'entity' )
            ->from( $this->getEntityName(), 'entity' );

        foreach ( $criteria as $field => $value ) {
            // IF INTEGER neq, IF NOT notLike
            if($this->getEntityManager()->getClassMetadata($this->getEntityName())->getFieldMapping($field)["type"]=="integer") {
                $qb->andWhere( $expr->neq( 'entity.' . $field, $value ) );
            } else {
                $qb->andWhere( $expr->notLike( 'entity.' . $field, $qb->expr()->literal($value) ) );
            }
        }

        if ( $orderBy ) {

            foreach ( $orderBy as $field => $order ) {

                $qb->addOrderBy( 'entity.' . $field, $order );
            }
        }

        if ( $limit )
            $qb->setMaxResults( $limit );

        if ( $offset )
            $qb->setFirstResult( $offset );

        return $qb->getQuery()
            ->getResult();
    }

}

Использование такое же, как у метода findBy, пример:

$entityManager->getRepository( 'MyRepo' )->findByNot(
    array( 'status' => Status::STATUS_DISABLED )
);

Ответ 5

Я решил это довольно легко (без добавления метода), поэтому я буду делиться:

use Doctrine\Common\Collections\Criteria;

$repository->matching( Criteria::create()->where( Criteria::expr()->neq('id', 1) ) );

Кстати, я использую модуль ORM Doctrine из Zend Framework 2, и я не уверен, совместим ли это в любом другом случае.

В моем случае я использовал конфигурацию элемента формы, например: показать все роли, кроме "гостя" в массиве переключателей.

$this->add(array(
    'type' => 'DoctrineModule\Form\Element\ObjectRadio',
        'name' => 'roles',
        'options' => array(
            'label' => _('Roles'),
            'object_manager' => $this->getEntityManager(),
            'target_class'   => 'Application\Entity\Role',
            'property' => 'roleId',
            'find_method'    => array(
                'name'   => 'matching',
                'params' => array(
                    'criteria' => Criteria::create()->where(
                        Criteria::expr()->neq('roleId', 'guest')
                ),
            ),
        ),
    ),
));