Symfony Doctrine findOneBy with not equal to - symfony

I need to find a phone number in a recording where the contract ID is not equal to current contract ID.
It is easy to find in a specific contract ID. $value is the entity instance in my custom validator.
$existingPhone = $this->contractRepository->findOneBy(['phone' => $value->getPhone(), 'contractId' => $value->getContractId()]);
but how to find in other than the current contract ID?

You need to create a method in your contractRepository, and use the Doctrine QB.
$qb = $this->createQueryBuilder('c');
$qb
->where('c.phone = :phone')
->andWhere(
$qb->expr()->neq('c.contractId', 'contractId')
)
->setParameters([
'phone' => $phone,
'contractId' => $contractId,
])
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();

Related

symfony3 doctrine. Make condition for related records

i have entity ShopGoods with relation manyToMany to entity ShopCategory. That's my method for get list of goods:
public function getListByFilter(ShopGoodsFilter $filter) {
$qb = $this->createQueryBuilder('goods')
->select('goods')
->leftJoin('goods.categories', 'categories')
->where('categories.id = :category_id')
->andWhere('goods.status=1')
->andWhere('categories.status != 0') // it's my try...
->setParameter('category_id', $filter->getCategory()->getId())
->setMaxResults($filter->getLimit())
->setFirstResult($filter->getOffset());
return [
'data' => $qb->getQuery()->getResult(),
'total' => $this->getTotalByFilter($filter)
];
}
I can't understand how make condition to get goods with categories.status = 1 for all related categories.
You could use something like:
$qb = $this->createQueryBuilder('goods')
->select('goods')
->leftJoin('goods.categories', 'categories', 'WITH', 'categories.status = 1')

DQL findBy default query

What is DQL findBy() query syntax?
Like this:
$this->getDoctrine()->getRepository("AppBundle:Users")->findBy($queryWhere);
It will create criteria for WHERE CLAUSE
$repository->findBy(['email' => 'test#test.com', 'city' => 'Berlin'])
SELECT * FROM table WHERE email = "test#test.com" AND city = "Berlin"
if you are interested, you can take a look in the method getSelectSQL under the following link
http://www.doctrine-project.org/api/orm/2.5/source-class-Doctrine.ORM.Persisters.Entity.BasicEntityPersister.html#877-891
This is typically used with a property of the entity. It takes an array with the key as the property name on the entity and the value as what you're searching for.
Examples:
$this->getDoctrine()
->getRepository('AppBundle:Users')
->findBy(['id' => $id])
;
$this->getDoctrine()
->getRepository('AppBundle:Users')
->findBy(['userName' => $userName])
;
$this->getDoctrine()
->getRepository('AppBundle:Users')
->findBy(['email' => $email])
;
You can read more about it here: https://symfony.com/doc/current/doctrine.html#fetching-objects-from-the-database

Symfony2 findBy+indexBy

In query builder you can specify which field should be used as array index:
$qb = $em->createQueryBuilder();
$qb->select('s');
$qb->from('models\Settings', 's', 's.key'); // here the magic
$result = $qb->getQuery()->getResult();
//here $result[key] is entity
Anybody knows how to add indexBy(not in DB, but index of array of results) to the findBy method, or make findBy-like method for repository, something like:
$clients = $clientRepository->findBy(['id' => $clients], [indexBy=>id]);
OR
$clients = $clientRepository->myFindByWithIndexBy(['id' => $clients], 'id');
I need a method with filter criteria (where) and it should return entities indexed by id.
Second argument to findBy is for ordering results (indexing in database context is another thing).
$repo->findBy(['id'=>$clients], ['id'=>'asc']); // reverse by changing 'asc' to 'desc'

Doctrine / Symfony: convert custom type to database value before using QueryBuilder

I have defined a custom Doctrine data type for Uuid. When I search for an object using find($uuid), it works correctly, i.e. the attribute is converted using convertToDatabaseValue() before executing the query, and converted back with convertToPhpValue() when value is retrieved.
The conversion doesn't work if I use the QueryBuilder. Example:
$qb = $this->createQueryBuilder('s');
$qb = $qb->where( //some conditions...
$qb->expr()->eq( 's.uuid', ':uuid' ))->setParameter( 'uuid', $uuid );
I found two similar unanswered questions:
Symfony Doctrine datatype only works in findBy not querybuilder
Doctrine 2 Custom Types
It looks like that the conversion is in fact ignored.
How can I force the conversion of the parameter before executing the query? Is there a way to access the convertToDatabaseValue() function of the custom data type from the repository?
Thanks
Yes setParameter() has third parameter, but the type of third param as string is worked for me not the object.
You can do it in following way.
$qb = $this->createQueryBuilder('s');
$qb = $qb->where( //some conditions...
$qb->expr()->eq( 's.uuid', ':uuid' ))->setParameter( 'uuid', $uuid, 'uuid' );
If you dont know what exactly key is for datatype 'uuid' is.
Then use print_r(Type::getTypesMap()); to get list of all dataypes added.
In my case it was
Array
(
[array] => Doctrine\DBAL\Types\ArrayType
[simple_array] => Doctrine\DBAL\Types\SimpleArrayType
[json_array] => Doctrine\DBAL\Types\JsonArrayType
[object] => Doctrine\DBAL\Types\ObjectType
[boolean] => Doctrine\DBAL\Types\BooleanType
[integer] => Doctrine\DBAL\Types\IntegerType
[smallint] => Doctrine\DBAL\Types\SmallIntType
[bigint] => Doctrine\DBAL\Types\BigIntType
[string] => Doctrine\DBAL\Types\StringType
[text] => Doctrine\DBAL\Types\TextType
[datetime] => Doctrine\DBAL\Types\DateTimeType
[datetimetz] => Doctrine\DBAL\Types\DateTimeTzType
[date] => Doctrine\DBAL\Types\DateType
[time] => Doctrine\DBAL\Types\TimeType
[decimal] => Doctrine\DBAL\Types\DecimalType
[float] => Doctrine\DBAL\Types\FloatType
[binary] => Doctrine\DBAL\Types\BinaryType
[blob] => Doctrine\DBAL\Types\BlobType
[guid] => Doctrine\DBAL\Types\GuidType
[geometry] => CrEOF\Spatial\DBAL\Types\GeometryType
[point] => CrEOF\Spatial\DBAL\Types\Geometry\PointType
[polygon] => CrEOF\Spatial\DBAL\Types\Geometry\PolygonType
[linestring] => CrEOF\Spatial\DBAL\Types\Geometry\LineStringType
)
And my doctrine code was something like this.
$queryBuilder = $this->createQueryBuilder('c');
$queryBuilder
->where('st_contains(:polygon, point(c.latitude, c.longitude) ) = 1')
->setParameter('polygon', $city->getPolygon(), 'polygon');
Here's the solution: the function setParameter() has a third argument $type which is used to declare the typology of the parameter. The custom declared type can be retrieved with the getType() function of the Doctrine Type class:
$qb = $this->createQueryBuilder('s');
$qb = $qb->where( //some conditions...
$qb->expr()->eq( 's.uuid', ':uuid' ))->setParameter( 'uuid', $uuid, Type::getType('uuid') );

Symfony2 - list of translated values

I'm using symfony2.4 + sonata + gedmo + a2 lix 1.x
I have one entity name "propriete" with his own translation entity (AbstractPersonalTranslation)
I'm able to create a admin form to CRUD the entity with translation tab (OK).
Now I want to display a part (filter on famille for instance) of the translated values of Propriete in an other admin form.
I tried to create a QueryBuilder
->add('firingTypes', 'entity', array(
'class' => 'Sal\RefBundle\Entity\Propriete',
'query_builder' => function(ProprieteRepository $er) {
return $er->queryMyProprieteEn('u');
}))
From repository:
public function queryMyProprieteEn() {
$qb = $this->createQueryBuilder('u')
->andWhere("u.famille=:famille")
->setParameter("famille", "139");
$query = $qb->getQuery();
$query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker');
$query->setHint(\Gedmo\Translatable\TranslatableListener::HINT_TRANSLATABLE_LOCALE, 'en');
return $query->getResult();
}
But of course I have the following error "Expected argument of type Doctrine\ORM\QueryBuilder", "array" given"
How to handle to create a combobox/checkbox of translated values from a main form ?
Please help
Regards

Resources