Doctrine Query builder for simple search - doctrine-orm

Hi I am trying to write a simple search query using QueryBuilder. I have a single table with fields: Name, Description, Code.
Basically I want to check if an entered keyword is in any of the fields.
public function searchProducts( $keyword )
{
$qb = $this->productRepository->createQueryBuilder('u');
$qb->add('where' , 'u.name LIKE :search');
$qb->add('where' , 'u.description LIKE :search');
$qb->add('where' , 'u.code LIKE :search');
$qb->setParameter('search', '%'.$keyword.'%');
}
How do I add the orX context to this?

public function searchProducts( $keyword )
{
$qb = $this->productRepository->createQueryBuilder('u');
$qb->add('where', $qb->expr()->orX(
$qb->expr()->like('u.name', ':search'),
$qb->expr()->like('u.description', ':search'),
$qb->expr()->like('u.code', ':search')
))
$qb->setParameter('search', '%'.$keyword.'%');
}
I think this should work for you.
Additional I'm not sure, but isnt there a select/from missing like this:
$qb->add('select', 'u')
->add('from', 'User u')
I have taken it from the doctrine2 ORM Doc:
Docu

Related

Complex QueryBuilder expresion in createQuery() with Sonata Admin

I'm using Symfony 4.2 and Sonata Admin bundle and I'm trying to display a specific list in one of my admin list view.
I want to display the lastest user by group. I created the SQL query and I'm now trying to translate it to QueryBuilder.
SELECT * FROM users
WHERE (created_at, group_id) IN (
SELECT MAX(created_at), group_id
FROM users
GROUP BY group_id)
My createQuery function in my Sonata Admin class :
public function createQuery($context = 'list')
{
$container = $this->getConfigurationPool()->getContainer();
$em = $container->get('doctrine.orm.entity_manager');
$expr = $em->getExpressionBuilder();
$subQuery = $em->createQueryBuilder()
->select('MAX(c.createdAt), c.group')
->from('ApiBundle:Configuration', 'c')
->groupBy('c.group')
->getDQL();
$query = parent::createQuery($context);
$alias = $query->getRootAlias();
$query->where($expr->in('('.$alias.'.createdAt, '.$alias.'.group)', $subQuery));
}
Unfortunately it is not working and I'm not sure it's the right way to do it.
I could make it work with only selecting the createdAt in the in() expression but it's not what I want to have at the end.
Here is the error I got.
[Syntax Error] line 0, col 77: Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got ','
How can I make it work using QueryBuilder ?
Thank you.

Pagerfanta does not like my doctrine query

In an application built on the symfony 4 framwork, I use a query in my user repository to find users with a specific role, that looks like this:
public function findByRole($role)
{
$qb = $this->_em->createQueryBuilder();
$qb->select('u')
->from($this->_entityName, 'u')
->where('u.roles LIKE :roles')
->setParameter('roles', '%"'.$role.'"%');
return $qb->getQuery()->getResult();
}
Now this query works well in general, but whenever I use it in combination with pagerfanta i encounter a problem. For example whenever I use the following in a controller:
$em = $this->getDoctrine()->getManager();
$query = $em->getRepository(User::class)->findByRole('ROLE_ADMIN');
$pagerfanta = $this->paginate($request, $query);
I get the error: "Call to a member function setFirstResult() on array".
To get around this problem I use:
$em = $this->getDoctrine()->getManager();
$query = $em->getRepository(User::class)->createQueryBuilder('u')
->andWhere( 'u.roles LIKE :role')
->setParameter('role', '%"ROLE_ADMIN"%');
$pagerfanta = $this->paginate($request, $query);
This works with pagerfanta without any problems. I just do not understand what is wrong with the first query (which does work whenever I do not use pagerfanta). Any ideas?
In order to make it work, just remove "->getQuery()->getResult();".

Doctrine Orm - Searching embedded associations

I have an Asset Entity that uses an embedded association:
/**
* #ORM\Entity
*/
class Asset
{
....
/**
* #ORM\Embedded(class="Money\Money")
*/
private $code;
I want to search this class and my first instinct was to do something like this:
public function findOneByCurrencyCode(string $currencyCode)
{
$qb = $this->assetRepository->createQueryBuilder('asset');
$qb->innerJoin('asset.code', 'code')
->where('code.currency = :currency')
->setParameter('currency', $currencyCode);
$result = $qb->getQuery()->getOneOrNullResult();
return $result;
}
This, however, returns the following:
[Semantical Error] line 0, col 65 near 'code WHERE code.currency': Error:
Class Domain\Asset\Asset has no association named code
How do you search embedded classes?
EDIT:
I can get a result by doing something like this, however, this I feel is a hack:
$query = "SELECT * from asset where code_currency='BTC';";
$statement = $this->objectManager->getConnection()->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
return $result;
I tried a bunch of different things and managed to get the answer:
$qb = $this->assetRepository->createQueryBuilder('asset');
$qb->where('asset.code.currency = :currency')
->setParameter('currency', $currencyCode);
$result = $qb->getQuery()->getOneOrNullResult();
return $result;
Turns out no inner join is required. Not sure why and perhaps someone can answer this in time, however the above appears to work with embedded objects
Hope this helps someone else.
"Embedded associations" does NOT exist. So, you doesn't need JOINS.
An embedded is part of your entity along with the others properties.
You have to do something like that:
SELECT u
FROM User u
WHERE u.address.city
(In this query, your entity is User, your embedded is Address and *city is the property of your
embedded).
It's pretty good explained in Doctrine documentation:
Doctrine embeddables

Symfony : Create a queryBuilder between two entities without mapping

I have two entities (there is no relation between the two entities): A: Relation and B: Post.
I get every post from the current user to display them on the homepage with this request:
public function getPostsCurrentUser($currentUser)
{
$qb = $this->createQueryBuilder('p');
$qb->where('p.member = :member')
->setParameters(['member' => $currentUser])
->orderBy('p.created', 'DESC');
return $qb->getQuery()->getResult();
}
In the example "A: Relation" the user 2 follow the user 1. When a user follow an other user, I would like to also display on the homepage every post of users that the current user are following.
I don't see how to create this request. Can anybody help me ?
Thanks
In the sense of http://sqlfiddle.com/#!9/c5a0bf/2, I would suggest something like the following which uses a subquery to select the ids of all followed users:
class PostRepository {
public function getPostsOfUser($id) {
$query = $this->getEntityManager()->createQuery(
"SELECT p.content
FROM AppBundle:Post p
WHERE p.member = :id
OR p.memberId IN (
SELECT r.friend
FROM AppBundle:Relation r
WHERE r.user = :id
)
ORDER BY p.created DESC"
);
return $query->setParameter('id', $id)
->getResult();
}
}

Doctrine paginator

I'm running into a problem with the Doctrine Paginator.
In my repository I have a function to retrieve a specific dataset.
I use the querybuilder for this:
{myEntityRepository}->createQueryBuilder($alias)
In order to select only specific fields I use the following:
if (count($selectFields) > 0) {
$qb->resetDQLPart('select');
foreach ($selectFields as $selectField) {
$qb->addSelect($alias . '.' . $selectField);
}
}
This works fine when I retrieve the whole set like this:
$query = $qb->getQuery();
$data = $query->getResult(AbstractQuery::HYDRATE_ARRAY);
But it fails when I use the paginator:
$paginator = new Paginator($qb, $fetchJoinCollection = false);
$total = $paginator->count(),
$data = $paginator->getQuery()->getResult(AbstractQuery::HYDRATE_ARRAY)
I get the error:
Not all identifier properties can be found in the ResultSetMapping:
relationID\vendor\doctrine\orm\lib\Doctrine\ORM\Query\Exec\SingleSelectExecutor.php(38)
Question: Why does the paginator fail when I select only specific fields?
Am I overlooking something? Or am I doing it wrong all together?
i am using this solution.
add use statements
use Zend\Paginator\Paginator;
use DoctrineORMModule\Paginator\Adapter\DoctrinePaginator as DoctrineAdapter;
use Doctrine\ORM\Tools\Pagination\Paginator as ORMPaginator;
in your action
$viewModel = new ViewModel();
$entityManager = $this->getServiceLocator()
->get('Doctrine\ORM\EntityManager');
$queryBuilder = $entityManager
->createQueryBuilder();
$queryBuilder->add('select', new Expr\Select(array('t.id', 't.name')));
$queryBuilder->add('from', 'Application\Entity\Table t');
$adapter = new DoctrineAdapter(
new ORMPaginator(
$queryBuilder
)
);
$paginator = new Paginator($adapter);
$paginator->setDefaultItemCountPerPage(20);
$page = (int)$this->params()->fromQuery('page');
if($page) $paginator->setCurrentPageNumber($page);
$viewModel->results = $paginator;
return $viewModel;
Doctrine is trying to hydrate a relationship outlined by your YAML file, using a field that doesn't exist because you've excluded it from your SELECT statement. Take a look at your mapping file to figure out what you need to add back in.
I would think that it's only complaining with the Paginator because the field is not being accessed (and therefore not being lazy-loaded) when you don't use the Paginator.
As an aside (and with zero understanding of your stack, so YMMV) I would avoid making a habit of SELECTing reduced result sets, as you'll find yourself running into odd issues like this all the time. If you do need extra performance, you'd be better off putting a good old caching layer in place...