Doctrine joined inheritance, disable with queryBuilder - symfony

I have defined an entity as:
#ORM\InheritanceType("JOINED")
Which works fine.
When trying to execute a simple query as:
$_builder = $this->_em->createQueryBuilder();
$_builder->select('COUNT(us.id)')
->from('TbBundle:UserStatus', 'us')
->where('us.user = :user')
->setParameter('user', $user);
return $_builder->getQuery()->getSingleScalarResult();
Doctrine will produce a query with some unnecessary left joins due to my inheritance architecture. Can I disable it for this query with queryBuilder in any way?
The goal:
I want to build count query using query builder but execute it without any inheritance influence so the executed query is as simple as:
SELECT COUNT(us.id) FROM table_name us WHERE us.user_id = 34;
I could write it using raw sql and get connection from entityManager but that's ugly.

Related

WHERE ... IN query with sub-query in Doctrine queryBuilder or equivalent

In my Symfony 4 project I have a User entity and a UserRepository.
I'm trying to implement the equivalent of this SQL query in the QueryBuilder(Doctrine 2) or even in DQL.
SELECT * FROM user WHERE account_manager_id IN (SELECT id FROM user WHERE account_manager_id = :managerAdminId AND roles LIKE '%ROLE_MANAGER%')
Or maybe use a different syntax.
I tried different things, but couldn't figure out how to write the WHERE ... IN with the sub-query.
This is all I could come up with, which I don't like because it fires multpiple queries for something I could do with a single one:
//App\Repository\UserRepository
public function getPublishersOfManagers($managerAdminId)
{
//SELECT * FROM user WHERE account_manager_id IN (SELECT id FROM user WHERE account_manager_id = :managerAdminId AND roles LIKE '%ROLE_MANAGER%')
$managerIds = $this->createQueryBuilder('u')
->select('u.id')
->where('u.roles LIKE :role')
->setParameter('role' , '%ROLE_MANAGER%')
->andWhere('u.accountManager = :managerAdminId')
->setParameter('managerAdminId' , $managerAdminId)
->getQuery()->getArrayResult();
$publishers = [];
foreach ($managerIds as $id) {
$publishers[] = $this->createQueryBuilder('u')
->select('u')
->where('u.roles LIKE :role')
->setParameter('role' , '%ROLE_PUBLISHER%')
->andWhere('u.accountManager = :managerAdminId')
->setParameter('managerAdminId' , $id)
->getQuery()->getResult();
}
return $publishers;
}
your query can be turned into something without a sub-query, but with a join instead, which should be equivalent (and should have the same runtime/complexity)
SELECT u
FROM user u
LEFT JOIN user am ON (am.id=u.accountManager)
WHERE am.roles LIKE '%ROLE_MANAGER%'
AND am.accountManager=:managerAdminId
AND u.roles LIKE '%ROLE_PUBLISHER%'
which can be translated into querybuilder accordingly (I have to assume, that you did not define your associations ... which I find disturbing, but you probably have your reasons):
return $this->createQueryBuilder('u')
->leftJoin('App\Entity\User', 'am', 'WITH', 'am.id=u.accountManager')
->andWhere('am.roles LIKE :role')
->setParameter('role', '%ROLE_MANAGER%')
->andWhere('am.accountManager = :managerAdminId')
->setParameter('managerAdminId', $managerAdminId)
->andWhere('u.roles LIKE :role2')
->setParameter('role2', '%ROLE_PUBLISHER%')
->getQuery()->getResult();
there is also the options of actually using sub-queries, but using sub-queries imho is always inconvenient - and ugly.
(you might have a look into writing just plain DQL queries, you might feel more at home ...?)
According to DQL query examples section within Doctrine's DQL documentation you need to either use EXISTS keyword within DQL query or use exists() method of Expr class.

CreateQueryBuilder on an association table that has no entity

I have an association table, that has no entity itself, inside an entity. I can do a raw or native query on it but I want to use createQueryBuilder on it. How can I?
Here is the raw query that I want to convert to createQueryBuilder:
$sql = 'SELECT t.* FROM tasks t LEFT JOIN question_tasks qt ON t.id = qt.task_id WHERE qt.question_id = :qtId';
$rsm = new ResultSetMappingBuilder($this->_em);
$rsm->addRootEntityFromClassMetadata(Task::class, 't');
$query = $this->_em->createNativeQuery($sql, $rsm);
$query->setParameter('qtId', $questionId);
return $query->getResult();
Thank you.
It's kind of impossible use Doctrine ORM without entity. QueryBuilder just converts down to DQL. DQL make queries over your object model.
Says documentation
You need to think about DQL as a query language for your object model,
not for your relational schema.
Check docs here Doctrine Query Language

Doctrine duplicating query results?

I have the following code
$this->em = $this->container->get('doctrine.orm.entity_manager');
$qb = $this->em->getRepository('CoreBundle:ServiceProvider')->createQueryBuilder('c');
$qb->select('count(venue.id) as vencount');
$qb->from('CoreBundle:ServiceProvider','venue');
$count = $qb->getQuery()->getOneOrNullResult()['vencount'];
which is write its returning a number of venues but the problem is that this number is mistaken because in the ServiceProvider table i have only 5 records but this query is returning 25. I tried to add a new record so they are 6 and yes the result was 36.
So I added group by the id and it fixed the issue anyone can tell me why is this happening ?
It's because when you create a query from a repository Doctrine assumes its a select and inject the select and from clausule's for you.
This is the sql you get from using the getRepository method:
SELECT count(i0_.id) AS sclr_0 FROM Entity i1_, Entity i0_
(Note that the entity is twice in the FROM).
Using just:
$qb = $this->em->createQueryBuilder();
$qb->select('count(venue.id) as vencount');
$qb->from('CoreBundle:ServiceProvider','venue');
You get:
SELECT count(i0_.id) AS sclr_0 FROM Entity i0_
Which is probably what you are looking for.
Another alternative is to get it from the repository but clear the sql parts with:
$qb = $this->em->getRepository('CoreBundle:ServiceProvider')->createQueryBuilder('c')->resetDQLParts();
But this way you lost the very purpose of using the repository in the first place.

Symfony2 Query with complex SQL in Repository

Bit of background first: we have a well evolved solution using Symfony1 and Propel which need to be migrated forward in time so I'm investigating migrating it to Symfony2.8 (with Doctrine).
I've not found a solution yet to having some SQL running it and then "hydrating" the results to object(s).
Any ideas.
Essentially I want to be able to do
$em = $this->getDoctrine()->getEntityManager();
$conn = $em->getConnection();
$sql = "SELECT xxxx";
$stmt = $conn->prepare($sql);
$stmt->bindValue(1, $siteId);
$rs = $stmt->execute();
$icount=0;
while ($rs->getnext())
{
$entity[$icount] = new Entity();
$entity[$icount] = hydrate($rs);
$icount++;
}
(those knowing propel will recognise this)
And I do get that if there is more than one entity in the query this should be in a service class of some kind.
I'd look into native SQL queries in doctrine. You can run regular SQL queries and get them hydrated into doctrine objects, with a little extra work.
Documentation here

Doctrine DQL Delete from relation table

Using Doctrine 2 and Symfony 2.0.
I have two Doctrine entities (let's suppose EntityA and EntityB).
I have a ManyToMany relation between them. So a EntityA_EntityB table has been created in database.
Using DQL or QueryBuilder, how can I delete from that relation table EntityA_EntityB?
Docrtine offers something like this to perform something similar:
->delete()
->from('EntityA a')
->where('a.id', '?', $id);
But I don't really get how to perform the deletion of row from the relation table.
$em = ...; // instance of `EntityManager`
// fetch both objects if ID is known
$a = $em->getRepository("YourProjectNamespace:EntityA")->find($id_of_A);
$b = $em->getRepository("YourProjectNamespace:EntityB")->find($id_of_B);
// suppose you have `EntityA::getObjectsOfTypeB` which retrieves all of linked objects of type `EntityB`.
// This method return instacne of ArrayCollection
$a->getObjectsOfTypeB()->removeElement($b);
$em->flush();
Something like this?
Basically, you need to remove related object from collection rather than delete relation itself. you want to remove relation directly you can always use pure SQL, but in DQL that is not possible.
Raw DELETE SQL statement via DBAL Connection object
$conn = $this->getDoctrine()->getManager()->getConnection();
$stmt = $conn->prepare("DELETE FROM EntityAEntityB WHERE id_b IN (:ids_of_b)");
$stmt->bindParam('ids_of_b', $to_delete_ids); // BEWARE: this array has to have at least one element
$stmt->executeUpdate();

Resources