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();".
Related
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
In Symfony3 I'm running
php app/console generate:doctrine:entity --entity=AcmeBlogBundle:Post
It creates 2 files: Post (in entity folder) and PostRepository (in repository folder extending \Doctrine\ORM\EntityRepository)
Everything is fine until I try to run the following repository-custom-function in my controller
$rir = $this->getDoctrine()->getRepository("AcmeBlogBundle:Post");
$replacementInstruction = $rir->getOneBy(
array("id" => 6)
);
My custom repository function is as follow
public function getOneBy($option)
{
$alias = "p";
$fields = $this->prepareRequestSelectFields("p");
$qb = $this->createQueryBuilder('Post');
$qb->select($fields)
->from('AcmeBlogBundle:Post', $alias)
->where($alias . '.id = :id')
->setParameter('id', 6)
;
$result = $qb->getQuery()->getResult();
}
private function prepareRequestSelectFields($alias)
{
return $alias. ".id";
}
In my database there are 10 posts with id from 1 to 10, so I expect it to return 1 result, however it return correct Post (id 6) 10 times
Why is that?
p.s. if I move the query builder to a custom service wrapper e.g. PostManager it works just fine (returning 1)
This doesn't really answer my question but apparently createQueryBuilder() in EntityRepository and in EntityManager are different, thanks to https://maltronic.io/2014/12/22/doctrine-createquerybuilder-entitymanager-vs-entityrepository/
So in my EntityRepository it should be
...
$qb = $this->createQueryBuilder('p'); // this should be the alias
$qb->select($fields)
// ->from('AcmeBlogBundle:Post', $alias) // remove this
->where($alias . '.id = :id')
->setParameter('id', 6)
;
...
Personally I dislike how 2 different functions has the same name, but I guess it's fine because one is from Doctrine and one is from Symfony. They are decoupled
edit Actually I might be wrong, they are both from Doctrine ... sigh
Still tho, it doesn't answer why in my original code, it returns multiple time
What about getSingleResult() rather than getResult() ? And you should maybe use the doctrine method findOneBy()
You can use the helper methods provided by the repositories, allowing you to fetch one or multiples entities from repositories with dynamic method names, in your case you want to fetch one post by id:
//fetch one
$replacementInstruction = $this->getDoctrine()->getRepository("AcmeBlogBundle:Post")->findOneById(6);
For information, fetching all entities is done with ->findByProperty
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...
I'm looking at Caching and how to use it in Doctrine.
I've got the following in my Zend Framework Bootstrap.php:
// Build Configuration
$orm_config = new \Doctrine\ORM\Configuration();
// Caching
$cacheOptions = $options['cache']['backendOptions'];
$cache = new \Doctrine\Common\Cache\MemcacheCache();
$memcache = new Memcache;
$memcache->connect($cacheOptions['servers']['host'], $cacheOptions['servers']['port']);
$cache->setMemcache($memcache);
$orm_config->setMetadataCacheImpl($cache);
$orm_config->setQueryCacheImpl($cache);
$orm_config->setResultCacheImpl($cache);
I'm running a very simple query on my DB using:
self::_instance()->_em->getRepository('UserManagement\Users')->find('1');
And I'm not sure if I'm using caching properly, because with it on (as
per the above config) the query seems to take twice as long to execute
as with it disabled, is this right?
Thanks in advance,
Steve
I seem to have sorted this myself, sort of related to enter link description here. Basically, from what I understand a repository query like:
self::_instance()->_em->getRepository('UserManagement\Users')->find('1');
Will not cache the results. If the same query is executed again throughout the script processing, it will not perform the search and use the result it has in memory - this isn't the same as real caching, in my case using Memcache.
The only way to achieve this, is to override the Doctrine EntityRepository find() method in a custom repository with something like:
public function find($id)
{
// Retrieve an instance of the Entity Manager
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('u')
->from('UserManagement\Users', 'u')
->where('u.id = :id')
->setParameter('id', $id);
$query = $qb->getQuery();
$query->useResultCache(TRUE);
$result = $query->getSingleResult();
return $result;
}
Notably, the most important line from the above is $query->useResultCache(TRUE); - this informs the Application to cache the results.
Hope this helps.
The following would return the a random record with Doctrine:
$name = Doctrine::getTable('nametable')
->createQuery()
->select('name')
->orderBy('RAND()')
->fetchOne();
But I'm running CI2 + Doctrine2, and so it does not work Call to undefined method Doctrine::getTable()
I've tried
$data = $this->doctrine->em->getRepository('ORM\Project\Names')
->orderBy('RAND()')
->fetchOne();
But this does not work either: Uncaught exception 'BadMethodCallException' with message 'Undefined method 'orderBy'. The method name must start with either findBy or findOneBy!'
Perhaps findOneBy is what I want, but it expects an array.
Is there an elegant way to fetch a random record in this setup?
Edit:
This is what I've come up with:
$query = $this->doctrine->em->createQuery("select max(u.id) from ORM\Dynasties2\Femalenames u");
$result = $query->getSingleResult();
$highval = $result[1];
$random_name = rand(1,$highval);
$name = $this->doctrine->em->find('ORM\Dynasties2\Femalenames', $random_name);
$mother_name = $name->getName();
Surely there is a cleaner way??? Apparently there's no such thing as RAND() in CI2/Doctrine2, short of just writing a SQL query.
"orderBy" is not working when you try to access the repository. In this case you have to make a query with "createQuery" or the query builder "createQueryBuilder".
The other way is:
$data = $this->doctrine->em->getRepository('ORM\Project\Names')->findOneBy(array(
'field' => 'ASC or DESC'
));
Here you can test RAND instead ASC or DESC but i think the best way is to make a query.
You can define a function in your repository and make a query that you have all querys in your repo and not in your controller then your first example looks good.
This is what I've come up with:
$query = $this->doctrine->em->createQuery("select max(u.id) from ORM\Dynasties2\Femalenames u");
$result = $query->getSingleResult();
$highval = $result[1];
$random_name = rand(1,$highval);
$name = $this->doctrine->em->find('ORM\Dynasties2\Femalenames', $random_name);
$mother_name = $name->getName();
I assumed there was another way, but cannot discover it.