What is the format of the array returned using the getResult() method in the following example, using Doctrine and Symfony2:
$query = $this->_em->createQuery('SELECT p.id, p.nameProduct FROM ArkiglassProductBundle:Product p');
return $query->getResult();
And I would like to know how to access each case and print every row.
<?php
$query = $em->createQuery('SELECT u.username, u.name FROM CmsUser u');
$users = $query->getResults(); // array of CmsUser username and name values
echo $users[0]['username'];
taken from the doctrine documentation
Are you asking about "0" in $users[0]?
I hope I am not misunderstanding your question.
getResults() returns an array of database results. Once you've given your array a name you can access each element using the index.
Of course if you want to loop over it you will probably use a foreach loop so you won't have to use the index:
$products = $query->getResults();
foreach ($products as $product){
echo $product->id.' '.$product->nameProduct;
}
This said... this pseudo code is here for the sake of explanation. If you are using Symfony you will have to display your results in a view file, probably using twig like Manuszep did in his example.
In his case you will have to use a for in loop like he did.
The query returns an array of Users:
array(
0 => array(username => 'aaa', name => 'bbb'),
1 => array(username => 'ccc', name => 'ddd')
)
So the $users[0] element means the first user in the list.
You can use a for loop to iterate:
{% for user in users %}
{{ user.username }} - {{ user.name }}
{% endfor %}
Related
What is DQL findBy() query syntax?
Like this:
$this->getDoctrine()->getRepository("AppBundle:Users")->findBy($queryWhere);
It will create criteria for WHERE CLAUSE
$repository->findBy(['email' => 'test#test.com', 'city' => 'Berlin'])
SELECT * FROM table WHERE email = "test#test.com" AND city = "Berlin"
if you are interested, you can take a look in the method getSelectSQL under the following link
http://www.doctrine-project.org/api/orm/2.5/source-class-Doctrine.ORM.Persisters.Entity.BasicEntityPersister.html#877-891
This is typically used with a property of the entity. It takes an array with the key as the property name on the entity and the value as what you're searching for.
Examples:
$this->getDoctrine()
->getRepository('AppBundle:Users')
->findBy(['id' => $id])
;
$this->getDoctrine()
->getRepository('AppBundle:Users')
->findBy(['userName' => $userName])
;
$this->getDoctrine()
->getRepository('AppBundle:Users')
->findBy(['email' => $email])
;
You can read more about it here: https://symfony.com/doc/current/doctrine.html#fetching-objects-from-the-database
My problem that when i use the loop , the data inside don't show up ,
this is the code here im using the loop even " mes boutiques " dont show, , only "shirts & tops" show up
and this function where im calling this template in the controller
Your function affichDQL() must have a problem, you should test the result in your controller with dump($enseignes); to see if you haves results. You can add an check in your twig too with {% dump(enseignes) %}
Your template looks ok. The problem probably is in the repository method that probably return the DQL: a string representing the query in Doctrine.
I suspect you have a method like this in your entity method:
// retrieve the DQL string of what was defined in QueryBuilder
$dql = $qb->getDql();
So you need to replace with something like this:
// retrieve the associated Query object with the processed DQL
$query = $qb->getQuery();
// Execute Query
$result = $query->getResult();
return $result;
Hope this help
I want to use redirect in symfony to generate a url and at the same time I want to make a variable 'levels', accessible in the twig template but it does not seem to be working for me.
here is the code:
return $this->redirect($this->generateUrl('show_admin_panel'), array('levels' => $levels));
I got this error: The HTTP status code "1" is not valid.
and if I use this:
return $this->redirect($this->generateUrl('show_admin_panel', array('levels' => $levels) ) );
I get this error: Variable "levels" does not exist in AUIAraBundle:Admin:admin_panel.html.twig at line 10
this is the code in the twig template:
{% for level in levels %}
<li>{{level.letter}}</li>
{% endfor %}
You don't need to query that variable 'level' in the action that redirects, just do:
return $this->redirect($this->generateUrl('show_admin_panel'));
Then in your controller linked to your 'show_admin_panel', make sure query that variable and pass it to the render method
//$level = something;
return $this->render('AUIAraBundle:Admin:admin_panel.html.twig',
array(
'levels' => $levels
)
);
}
I've got a query set up in doctrine that I'm confident does what it's supposed to...it joins several tables so we can skip a bunch of extra queries to get data through foreign keys:
$posts = $this->getDoctrine()->getManager()
->createQuery('
SELECT a AS article, COUNT(c) AS comments
FROM ArticleBundle:Article a
LEFT JOIN CommentsBundle:Comment c WITH (c.article = a.id)
LEFT JOIN ImageBundle:Image i WITH (i.id = a.image)
GROUP BY a.id
ORDER BY a.timestamp DESC
')
->getResult();
I'm able to access the data quite succesfully, like so:
{% for post in posts %}
<div id="news-story">
<div class="title">{{ post.article.title }}</div>
<div class="comments">{{ post.comments }}</div>
...
{% endfor %}
The issue is, as soon as I add a second column ("i AS image") to the field list, it fails. I get the following message...
Item "article" for "Array" does not exist in ...
...and I can't quite figure out why. I would hope that I would be able to access the variables like {{ post.article.title }} and {{ post.image.path }} (which does exist, by the way)...but I can't.
Any thoughts would be greatly appreciated.
Thanks!
I think your confusion arises from the fact that you have created a query that returns a scalar result: COUNT(c)... along with objects.
This means that instead of returning an array of Article entities, as you expect (you are trying to use post.image) you actually get an associative array, where each member contains the count - post.comments and the article entity post.article.
n.b. If you want to access images associated with the article, you will need to use post.article.image.
I'll try and illustrate:
Your expecting an array of article objects that you can iterate over:
array(
[0] => ArticleEntity,
[1] => ArticleEntity,
[2] => ArticleEntity
)
What you actually get from your query
array(
[0] => array(
'article' => ArticleEntity,
'comments'=> 10
),
[1] => array(
'article' => ArticleEntity,
'comments'=> 3
),
[2] => array(
'article' => ArticleEntity,
'comments'=> 0
)
)
If you remove the scalar part of your query COUNT(c) AS comments then you will get the first example, leave it in and you will get the second example.
The Doctrine documentation on pure/mixed results is some good reading/explanation on this.
As a side note is there any reason you are writing raw SQL. For a start you can re-write the query using DQL to leverage some of the power Doctrine offers.
$qb = $this->getDoctrine()->getManager()->createQueryBuilder();
$qb
->select('article', 'image', 'COUNT(comments) as comment_count')
->from('ArticleBundle:Article', 'article')
->leftJoin('article.comment', 'comments')
->leftJoin('article.image', 'image')
->groupBy('article.id')
->orderBy('article.timestamp', 'DESC')
;
$posts = $qb->getQuery()->getResult();
I have 1 controller that passes 2 paginated set of results to a twig (as 2 arrays representing tables) using KnpPaginator Bundle.
While both tables show up and are paginated, I am not able to sort any of them.
Edit: When I change page of table 1, table 2's page also changes to that page number.
Trying to sort either of them returns: There is no component aliased by [t] in the given Query or There is no component aliased by [r] in the given Query.
The controller:
$em = $this->getDoctrine()->getEntityManager();
$pageSize = $this->container->getParameter('page_size');
$paginator = $this->get('knp_paginator');
/* Queries */
$queryTest = $em
->createQuery('
SELECT t FROM PanasonicTestEtAvisBundle:Test t
JOIN t.product p
WHERE p.id = :id
AND t.isDeleted = :isdeleted
ORDER BY t.creationDate DESC'
)->setParameter('id', $id)
->setParameter('isdeleted', '0');
$queryReview = $em
->createQuery('
SELECT r FROM PanasonicTestEtAvisBundle:Review r
JOIN r.product p
WHERE p.id = :id
AND r.isDeleted = :isdeleted
ORDER BY r.creationDate DESC'
)->setParameter('id', $id)
->setParameter('isdeleted', '0');
/* paginated results */
$paginationTest = $paginator->paginate($queryTest, $this->get('request')->query->get('page', 1), $pageSize);
// compact('paginationTest');
$paginationReview = $paginator->paginate($queryReview, $this->get('request')->query->get('page', 1), $pageSize);
// compact('paginationReview');
// compact('pagination');
return $this->render('PanasonicTestEtAvisBundle:Product:show.html.twig', array(
'paginationTest' => $paginationTest,
'paginationReview' => $paginationReview
));
The error shows up only when I pass both pagination (paginationTest & paginationReview), if I pass only one it works flawlessly.
Anyone can tell me how I can solve this problem?
Your example didn't work, because you use the same page variable "page" for both of pagination sets.
If you want to use two or more pagination sets in the same place, you must do this:
Your Controller:
...
$pagename1 = 'page1'; // Set custom page variable name
$page1 = this->get('request')->query->get($pagename1, 1); // Get custom page variable
$paginationReview = $paginator->paginate(
$queryReview,
$page1,
$pageSize,
array('pageParameterName' => $pagename1)
);
$pagename2 = 'page2'; // Set another custom page variable name
$page2 = this->get('request')->query->get($pagename2, 1); // Get another custom page variable
$paginationReview = $paginator->paginate(
$queryReview,
$page2,
$pageSize,
array('pageParameterName' => $pagename2)
);
return $this->render('PanasonicTestEtAvisBundle:Product:show.html.twig', array(
'paginationTest' => $paginationTest,
'paginationReview' => $paginationReview
));
Your view:
// PanasonicTestEtAvisBundle:Product:show.html.twig
{# First set #}
{% for test in paginationTest %}
<tr>
<td>{{ test.id }}</td>
</tr>
{% endfor %}
{{ paginationTest.render()|raw }}
{# Second set #}
{% for review in paginationReview %}
<tr>
<td>{{ review.id }}</td>
</tr>
{% endfor %}
{{ paginationReview.render()|raw }}
Enjoy!
It's 2017 and I got into similar problem. Just for reference, I'm using:
"knplabs/knp-paginator-bundle": "^2.5",
I was trying to run several functional tests with Symfony's crawler. Some of them were using Knp Paginator with such options:
[
'defaultSortFieldName' => 'voucher.id',
'defaultSortDirection' => 'DESC',
'wrap-queries' => true,
'defaultFilterFields' => ['voucherText.title']
]
while others with those options:
[
'defaultSortFieldName' => 'event.id',
'defaultSortDirection' => 'DESC',
'wrap-queries' => true,
'defaultFilterFields' => ['event.name', 'eventText.description']
]
Problem appeared with sorting parameter name, because both Paginators were using defaul 'sort' key, taking it from global $_GET array - you can check it yourself: Knp\Component\Pager\Event\Subscriber\Sortable\Doctrine\ORM\QuerySubscriber.
However the enigmatic part was the error being thrown:
UnexpectedValueException: There is no component aliased by [event] in the given Query
In order to avoid this weirdos/crappiness, I found a 'sortFieldParameterName' option, which you can add to all of your Paginators' options:
[
'sortFieldParameterName' => 'sort_event',
'defaultSortFieldName' => 'event.id',
'defaultSortDirection' => 'DESC',
'wrap-queries' => true,
]