Using an Entity's methods inside a query in Doctrine - symfony

I have a table of Customers with fields name, addressLine1, addressLine2 and postcode. The corresponding entity also has a method called address that returns the 2 address lines and the postcode concatenated together with comma/space separation, ignoring any empty fields.
I want to return a list of customers sorted by name and then address (for any customers with the same name). Currently I try
$this->getEntityManager()->createQuery(
'SELECT c FROM AppBundle:Customer c ORDER BY c.name ASC, c.address ASC'
)->getResult();
but I cannot use the method Customer::address() in the query like this. I get the error
Error: Class AppBundle\Entity\Customer has no field or association named address
Is there a way I can use an Entity's methods inside a query like this?

Short answer - no, and you don't really want to. You're conflating PHP logic with SQL logic. Your address() function is a pure PHP function. Even though it is using relationships within your entity, Doctrine itself has no way of knowing about it. Your function is literally returning a string, so how would it know how to convert that to SQL for your WHERE clause?
Just change your original query to this:
$this->getEntityManager()->createQuery('
SELECT c
FROM AppBundle:Customer c
ORDER BY c.name ASC, c.addressLine1 ASC, c.addressLine2 ASC, c.postcode ASC
')->getResult();
I suppose you could pseudo-do what you want like this:
Customer Entity:
public static function addressSort()
{
return ' c.addressLine1 ASC, c.addressLine2 ASC, c.postcode ';
}
and then do
$this->getEntityManager()->createQuery('
SELECT c
FROM AppBundle:Customer c
ORDER BY c.name ASC, ' . Customer::addressSort()
)->getResult();
However, now you're mixing PHP and SQL even further and I very highly recommend that you do NOT do this.

Related

Drupal entityQuery multiple node types and join

Looking to join multiple nodes via a query and join. Let's say one node has a matching ID of another field in another node. I would like to join them into an array so that I can output other fields with them indexed together on the same ID. Example: node1.nid and node2.field.target_id
How do I do this?
$nids = \Drupal::entityQuery('node')->accessCheck(FALSE)
->join('node2', 'n2', 'n.nid = n2.field.target_id');
->condition('type', 'node1', 'node2')
->sort('title')->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);
$response = array();
This is definitely doable and it looks like you're almost there, but it looks like you're combining the Database API with the Entity API, specifically trying to run Database joins on EntityQuery fetches.
Now, if you want to continue the Database query route, which may make it a little easier to join the values of multiple entities and output them, this is what I would recommend:
The first thing that I notice is that you're attempting to chain the join. Unfortunately, according to the Database API Docs
Joins cannot be chained, so they have to be called separately (see Chaining).
I have done similar to this with a join between two custom content types. Here is the code I used:
$connection = Database::getConnection();
if ($connection->schema()->tableExists('companies') && $connection->schema()->tableExists('users')) {
$query = $connection->select('companies', 'c');
$query->join('users', 'u', 'c.sourceid1 = u.sourceid1');
$results = $query->fields('u', ['destid1', 'sourceid1'])
->fields('c', ['destid1'])
->execute()
->fetchAll();
return $results;
}
Now this assumes that you've brought in Drupal\Core\Database\Database, but let's walk through the process.
$connection = Database::getConnection();
This is fetching the database connection for your site
if ($connection->schema()->tableExists('companies') && $connection->schema()->tableExists('users')) {
This is a check I always do to make sure the tables I'm working with exist.
$query = $connection->select('companies', 'c');
One of your tables needs to be the "base" table. In this case, I chose companies.
$query->join('users', 'u', 'c.sourceid1 = u.sourceid1');
This line is where the join actually happens. Notice that it's not chained, but it's own command. We're joining these tables, users and companies, on this sourceid1.
$results = $query->fields('u', ['destid1', 'sourceid1'])
->fields('c', ['destid1'])
->execute()
->fetchAll();
This is where I'm pulling whichever fields I want from both entities. In this case I want destid1 and sourceid1 from my user table and destid1 from my company table.
The ->execute() call actually runs the query, and ->fetchAll() returns an array of all matching results. This will get you to being able to JSONify all the things.
However, if you want to stick with the entityQuery route, that's also viable. My personal preference is to use a regular query for more complex things and an entityQuery if I just need to get a value from a single field or return a single entity.
For an entityQuery, well, that's a bit different. I wouldn't really recommend using an entityQuery for a join here. Instead, using entityTypeManager if you know or can get the matching value from both tables.
For example, let's assume that field_content_type_a_id on content type A matches field_related_type_a_id on content type B.
You could load one, let's go with type A for now:
// Get the current NID somehow... that's up to you
$entity_a = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
// Get the value of the field you want to match to the other content type
$matching_value = $entity_a->get('field_content_type_a_id')->getValue();
// Get the entities with matching type A values
$entity_b_array = \Drupal::entityTypeManager()->getStorage('node')
->loadByProperties(['field_related_type_a_id' => $matching_value]);
// Do something with $entity_b_array.

Doctrine Query reverse join?

I have these relations.
I need to retrieve all contents but order by star.content_Idcontent first.
It works with easy SQL:
SELECT content.idcontent
FROM content
LEFT JOIN star ON content.idcontent = star.content_Idcontent
ORDER BY star.content_Idcontent DESC,content.idcontent
But I don't know how to do it with Doctrine because content is not the owner of the relation.
Must I create a bidirectional relation or is there a way to make it work?
You can create a query in ContentRepository like:
$qb = $this
->createQueryBuilder('content')
->join(
'App\Entity\Star',
'star',
\Doctrine\ORM\Query\Expr\LeftJoin::WITH,
'content.idcontent = star.content_Idcontent '
)
->orderBy('star.content_Idcontent', 'DESC')
;
$qb->getResult();
Assuming that your Entity Star is located in App\Entity\Star

Doctrine2 QueryBuilder select entity and count of associated entities

I'm having a huge problem with ORM QueryBuilder. What I need to do is:
I need to fetch order with count of its products and plenty of associated entities (associated with order), but I assume they're not relevant here. I also need to order result by that count.
Could anyone give me an example of how this can be achieved? I would like to avoid "inline" DQLs if possible.
You can get data via Doctrine Query Builder.
You are supposed to left join products from Order and then group by order id. You can have COUNT(product.id) in your select statement and use the alias in order by clause to make your orders sorted. Below is a small code snippet from Repository.
/**
* #return \Doctrine\ORM\Query
*/
public function getHotelAndRoomType()
{
$qb = $this->createQueryBuilder('order')
->select('partial order.{id, orderId} as order, count(product.id) as total_products_in_order')
->leftJoin('AppBundle:Product', 'product', 'WITH', 'product.order = order.id')
->groupBy('order.id')
->orderBy('total_products_in_order', 'DESC')
;
return $qb->getQuery()->execute();
}
Note : Code not tested.

pagerfanta - DoctrineORMAdapter Sorting

Although I know this is trivial I'm stuck trying to implement the pagerfanta Paginator using the DoctrineORMAdapter, I want to paginate all entities sorted by id in descending order, the final SQL I want is this:
SELECT id, name FROM User ORDER BY id DESC LIMIT 0, 5;
Suppose I had users from A to Z and I want to limit them by 5 each page, what DoctrineORMAdapter is paginating results in User E to A listed in the first page, while what I actually expect is to see User Z to user V in the first page, U to Q in the second page and so on. The DQL I'm passing to DoctrineORMAdapter is as follow:
SELECT u FROM My\FluffyBundle\Entity\User u ORDER BY u.id DESC
On execution this is the final DQL for the first page:
SELECT DISTINCT id0 FROM (SELECT u0_.id AS id0, u0_.name AS name1 FROM User u0_
ORDER BY u0_.id DESC) dctrn_result LIMIT 5 OFFSET 0
Please note that when using the ArrayAdapter instead of DoctrineORM's it works as expected, but it's not a good idea to rely on ArrayAdapter when you have thousands of complex Doctrine Entities, not even with extra lazy loading :D.
This is the only relevant code:
$queryBuilder = $repo->createQueryBuilder('u')->orderBy('u.id', 'DESC');
$adapter = new DoctrineORMAdapter($queryBuilder);
$pager = new Pagerfanta($adapter);
$pager->setMaxPerPage(5);
Thanks.
This will help you:
$adapter = new DoctrineORMAdapter($queryBuilder, false);
Had the same problem this morning.
By default Pagerfanta is treating your query as one with joins. Setting second argument to false makes it use simple query handling.
In Kunstmaan Bundle, in AdminListConfiguration class, you have to overide function that is creating Pagerfanta, if you want to sort simple entity.

Symfony2 QueryBuilder join ON and WITH difference

I'm new with Symfony2 and I built successfully my first join through QueryBuilder and Doctrine 2.
Probably this is a stupid question but both on-line and in the Symfony2's methods I was unable to find anything for understanding the difference between the join clauses "WITH" and "ON".
For example this is my join code:
->leftJoin('EcommerceProductBundle:ProductData', 'pdata', 'WITH', 'prod.id = IDENTITY(pdata.product)')
It works good but if I put ON instead of WITH I get the following error:
[Syntax Error] line 0, col 200: Error: Expected
Doctrine\ORM\Query\Lexer::T_WITH, got 'ON'
Why? I've seen among the objects that there are both the T_ON and T_WITH like join clauses, but which is their usage difference? What is their uses like?
#florian gave you the correct answer but let me try to explain it on example:
In sql, joins are done like this:
SELECT * FROM category
LEFT JOIN product ON product.category_id = category.id
(or something like this)
Now in Doctrine, you don't need to use ON clause because doctrine knows that from relations annotations in your entities. So above example would be:
// CategoryRepository.php
public function getCategoriesAndJoinProducts()
{
return $this->createQueryBuilder("o")
->leftJoin("o.products", "p")->addSelect("p")
->getQuery()->getResult() ;
}
Both would fetch all categories and join products associated with them.
Now comes the WITH clause. If you want to join only products with price bigger than 50, you would do this in SQL:
SELECT * FROM category
LEFT JOIN product ON product.category_id = category.id AND product.price>50
In Doctrine:
// CategoryRepository.php
public function getCategoriesAndJoinProductsWithPriceBiggerThan($price)
{
return $this->createQueryBuilder("o")
->leftJoin("o.products", "p", "WITH", "p.price>:price")
->setParameter("price", price)->addSelect("p")
->getQuery()->getResult() ;
}
So, in reality you should never, ever use ON if you are using Doctrine. If you have a need for something like that, you can be almost sure that you screwed something else.
In theory, ON permits you to give the full join criterias, while WITH permits to add additional criterias to the default ones (IMHO).
But, what DQL permits is to avoid giving the JOIN criterias:
You just have to say: $qb->leftJoin('prod.pdata', 'pdata');
And doctrine2 will handle the join correctly.
Here is a related question about that: Can I use "ON" keyword in DQL or do I need to use Native Query?

Resources