Doctrine, NativeQuery, Join and Limit for first entity - symfony

I used Doctrine and NativeQuery (setResultMapping). In my query, I use multiple joins to fetch entities that are related using OneToMany. I want to create pagination only for my first entity (For in Html, one col and many data in one row (oneToMany)).
If I use LIMIT 0, 20, joins multiply the result and distorts it.
Can you help me ?

With DQL queries, Doctrine's Paginator is your man - Doctrine Docs. What concerns NativeQuery there seems to be a solution in this post - How to paginate a native query in Doctrine 2?

Related

Is it possible to convert DQL query builder to query builder?

I have a tree structure, it is managed by Gedmo\Tree. I want to make complex update for one field in subtree, this update requires join with another table, it is not supported by DQL. So I want to get DQL builder by Gedmo\Tree repository method childrenQueryBuilder, convert it to QueryBuilder and add update statement.
$dqlQueryBuilder = $repository->childrenQueryBuilder($node, ...);
$dqlQueryBuilder->resetDQLParts(['select', 'orderBy']);
$queryBuilder = convert($dqlQueryBuilder);
$queryBuilder->leftJoin('...', 'lj');
$queryBuilder->update('node.update', 'concat(node.field, lj.field)');
I know that I can write custom QueryBuilder, I just wonder if such conversions are possible by doctrine builtin tools or some 3-rd party libraries.
There's no such thing as SQLQueryBuilder in Doctrine, there's only QueryBuilder which is an DQL Query Builder. What you can do is to convert DQL to SQL by doing
$stringSql = $queryBuilder->getQuery()
->getSQL();
Once you have it you might play with native sql and then execute it as a raw sql.
Note: I'm not sure what exact DB Specific statement you mean, but there's a possibility to map DB Specific functions to DQL by making use of FunctionNode class. Once you have your function mapped to DQL you might accomplish it with DQL only.
Check documentation on how to work with custom DB functions in DQL

Symfony - Doctrine QueryBuilder produces wrong sql

I am trying to build a query via query builder.
$photosQuery = $photoRepository->createQueryBuilder('p')
->join('AppBundle:User', 'u')
->where('LOWER(p.title) LIKE :phrase OR LOWER(u.username) LIKE :phrase AND p.isActive = :isActive AND p.isModerated = :isModerated')
->setParameter('phrase', '%'.strtolower($phrase).'%')
->setParameter('isActive', true)
->setParameter('isModerated', true)
->getQuery();
It gives me
SELECT p0_.id AS id_0,
p0_.title AS title_1,
p0_.description AS description_2,
p0_.name AS name_3,
p0_.creation_date AS creation_date_4,
p0_.edit_date AS edit_date_5,
p0_.is_moderated AS is_moderated_6,
p0_.moderation_date AS moderation_date_7,
p0_.is_active AS is_active_8,
p0_.user_id AS user_id_9,
p0_.category_id AS category_id_10
FROM photos p0_
INNER JOIN users u1_ ON (LOWER(p0_.title) LIKE ?
OR LOWER(u1_.username) LIKE ?
AND p0_.is_active = ?
AND p0_.is_moderated = ?)
Why are my WHERE parameters in the join ON() portion and not a traditional WHERE?
Thank you!
Doctrine provides a wrapper around lower-level database connections that to not necessary have all the features present in DQL. As such, it emulates some features (such as named parameters, or splitting array parameters into multiple separate values).
You're seeing that in action here: the named parameters are converted into positional parameters in the raw query. Doctrine still knows what the mapping is, though, and is able to correctly order them when the query and parameters are sent to the server.
So the answer from jbafford explained some information Doctrine but did not explicitly answer why the ON was used instead of the WHERE, and it stems from a common mistake (of which I recently made as well).
In your query, when you use
->join('AppBundle:User', 'u')
you are simply telling the query builder that you need to join on the User table, but it doesn't specifically know that you want to join on the user association of your Photo entity. You may think - why doesn't this happen automatically? Well, imagine if you had 2 another association on your table that linked to a User entity as well (maybe a createdBy field or similar). In that case Doctrine wouldn't know the association you wanted.
So, instead the proper thing to do is join directly on your association rather than generically on the entity, like so:
->join('p.user', 'u')
and then Doctrine will handle the rest. I couldn't actually tell you why it uses the where() condition for the join, unless it's just assuming that's what you wanted, since it needs to know how to join on something.
So just remember that when you are joining on an association you already defined, join on the association as described in your entities rather than thinking of it in a straight SQL format where you'd join on the table.

How does Doctrine2 One-To-Many fetch=EAGER work?

I'm using Symfony 2.8 / Doctrine ORM 2.5.2.
I have 2 entities, Gallery OneToMany File
class Gallery
{
/**
* #var File[]
*
* #ORM\OneToMany(targetEntity="File", mappedBy="gallery", fetch="EAGER")
*/
private $files;
}
I see 2 things in the documentation.
First, now the OneToMany relationship does have the fetch=EAGER option (specified here). It was not there in previous versions.
Second, the manual setting for this fetch method per query seems not available for OneToMany but I don't know if the documentation is up-to-date as it states:
Changing the fetch mode during a query is only possible for one-to-one
and many-to-one relations.
I have anyway tried both, here is my query:
public function findWithEager()
{
$qb = $this->createQueryBuilder('g');
$query = $qb->getQuery();
$query->setFetchMode("CommonBundle\\Entity\\Gallery", "files", ClassMetadata::FETCH_EAGER);
return $query->getResult();
}
But when I do:
foreach ($galleryRepository->findWithEager() as $gallery) {
foreach ($gallery->getFiles() as $file) {
$file->getId();
}
}
Then I got 1+n queries. The first is SELECT * FROM Gallery and the n following ones are SELECT * FROM File WHERE id = :galleryId
I would like Doctrine to do 1+1 queries, the second one being SELECT * FROM File WHERE id IN (:galleryListIds)
Did I miss something? Is this behavior implemented in Doctrine?
The latest doctrine changelog states:
When marking a one-to-many association with fetch="EAGER" it will now
execute one query less than before and work correctly in combination
with indexBy.
It is not clear at all what is the expected behavior.
Any insight is welcome, thanks!
After much searching and some testing (using Doctrine ORM 2.5.6 on PHP 5.6) I have some results.
At this time it is not possible to get your Gallery entities with one query and all related File entities with a second query.
You have two options
Get Gallery and File entities in one query using Left Join.
This is what the ->find* methods do when you set fetch="EAGER" on your annotation.
You can do this manually with DQL: SELECT g, f FROM Gallery g LEFT JOIN g.files f
As noted in the docs, you cannot call ->setFetchMode('Gallery', 'files', ClassMetadata::FETCH_EAGER) on a DQL query to achieve the same result
... For one-to-many relations, changing the fetch mode to eager will cause to execute one query for every root entity loaded. This gives no improvement over the lazy fetch mode which will also initialize the associations on a one-by-one basis once they are accessed.
This will result in n additional queries being run immediately after your first query to fetch your Gallery entities.
Get Gallery entities with one query and lazy-load the File entities.
This is Doctrine's default behaviour (fetch="LAZY") and will result in 1 query plus an additional query for each set of Gallery#$files you access (1+n queries if you access them all).
Possible Future Option
There is a PR to add an EAGER_BATCHED fetch option which would do exactly what you want (fetch Gallery entities with one query then fetch all File entities with a second query) but there doesn't seem to be much happening with it, unfortunately.
Conclusion
If you're using the ->find* methods, fetch="EAGER" annotations will be respected. Doctrine will do this with a LEFT JOIN. Depending on your data set this could be ok or very expensive.
If you're writing DQL manually or using the query builder you must LEFT JOIN one-to-many relations AND remember to add any entities you want fetched to the select clause.
My preference is to write DQL whenever you want a one-to-many relation fetched eagerly because it makes your intention clear.

How correctly insert values in table using Doctrine ORM?

I use Symfony2 and Doctrine ORM. I have table "articleType" where I keep all possible article types. I need insert several values to that table only once, when table is created. My question is how and where I should do that? Because I just can't insert that values in controller with every request to that controller right? Maybe I should write down manually that inserts in Doctrine migration class?
It depends, but most of the time Doctrine Migrations are the way to go. Each migration is supposed to be applied just once and that's exactly what you need.

How do you join two tables in Doctrine2 using Query Builder if the table relationships are not setup?

I am currently using Symfony2 and Doctrine2 and am trying to join two tables together using query builder.
The problem I have is that all my annotated entities do not have the table relationships setup. I will at some point address this, but in the mean time I need to try and work round this.
Basically I have two tables: a product table and a product_description table. The product table stores the basic information and then I have a product_description table that stores the description information. A product can have one or more descriptions due to language.
I want to use query builder, so I can retrieve both the product and product_description results as objects.
At the moment I am using the following code:
// Get the query builder
$qb = $em->createQueryBuilder();
// Build the query
$qb->select(array('p, pd'));
$qb->from('MyCompanyMyBundle:Product', 'p');
$qb->innerJoin('pd', 'MyCompanyMyBundle:ProductDescription', 'pd', 'ON', $qb->expr()->eq('p.id', 'pd.departmentId'));
$query = $qb->getQuery();
$products = $query->getResult();
This gives me the following error:
[Syntax Error] line 0, col 71: Error: Expected Doctrine\ORM\Query\Lexer::T_DOT, got 'MyCompanyMyBundle:ProductDescription'
Can anyone point me in the right direction? I am up for doing it differently if there is an alternative.
Without having the relationships defined, I don't think you can join the tables. This is because when you use DQL, you're querying an object rather than a table, and if the objects are unaware of each other, you can't join them.
I think you should look at using a NativeQuery. From the docs:
A NativeQuery lets you execute native SELECT SQL statements, mapping the results according to your specifications. Such a specification that describes how an SQL result set is mapped to a Doctrine result is represented by a ResultSetMapping. It describes how each column of the database result should be mapped by Doctrine in terms of the object graph. This allows you to map arbitrary SQL code to objects, such as highly vendor-optimized SQL or stored-procedures.
Basically, you write raw SQL, but tell Doctrine how to map the results to your existing entities.
Hope this helps.

Resources