Get content of an ArrayCollection - symfony

I would like to upgrade my symfony 2 project from 2.3 to 2.7 LTS version. I have a problem in a repository to get result of a query. In 2.3, this query give me something :
public function findProtectedPublications( $steps, $start, $end)
{
$query= $this->getEntityManager()
->createQueryBuilder()
->select('d.pubRefs')
->from('ImpressionDemandBundle:Event', 'h')
->innerJoin('h.demand','d')
->where('d.protectedPublications = :pub')
->setParameter('pub', 1 )
->andWhere('h.date >= :start')
->setParameter('start', $start )
->andWhere('h.date <= :end')
->setParameter('end', $end )
->andWhere('h.stepId in (:steps)')
->setParameter('steps', $steps )
->orderBy('d.id','ASC')
->getQuery();
$results = $query->getResult();
$publications = array();
if ($results && ! empty ($results)){
foreach($results as $result){
$pubs = $result['pubRefs'];
if ($pubs && ! empty($pubs)){
foreach($pubs as $pub){
$publications[] = $pub;
}
}
}
}
return $publications;
}
But this code doesn't work in earlier version because $pubs variable in an ArrayCollection. So I changed the end of my code with this :
$results = $query->getResult();
$publications = array();
if ($results && ! empty ($results)){
foreach($results as $result){
$pubs = $result['pubRefs'];
var_dump($pubs);
if (! $pubs->isEmpty()){
$arrayPubs = $pubs->toArray();
foreach($arrayPubs as $pub){
$publications[] = $pub;
}
}
}
}
return $publications;
In this part, when I dump the $pubs variable, I have :
object(Doctrine\Common\Collections\ArrayCollection)#131 (2) {
["elements":"Doctrine\Common\Collections\ArrayCollection":private]=>
NULL
["_elements":"Doctrine\Common\Collections\ArrayCollection":private]=>
array(1) {
[0]=>
object(Impression\DemandBundle\Entity\Publication)#125 (5) {
["editor":"Impression\DemandBundle\Entity\Publication":private]=>
string(24) "Journal Le Monde 4-10-13"
["coauthors":"Impression\DemandBundle\Entity\Publication":private]=>
string(12) "Machin Machin"
["title":"Impression\DemandBundle\Entity\Publication":private]=>
string(57) "La tragédie de Lampedusa: s"émouvoir, comprendre, agir."
["nbPages":"Impression\DemandBundle\Entity\Publication":private]=>
float(1)
["nbCopies":"Impression\DemandBundle\Entity\Publication":private]=>
float(40)
}
}
}
So it seems that there are elements in this ArrayCollection, but the test $pubs->isEmpty() gives a true result, so I have nothing in $publications array.
Edit: In fact, the problem seems to be due to my data in the database : for an object previous from my upgrade, I have something like this in the database :
O:43:"Doctrine\Common\Collections\ArrayCollection":1:{s:54:"Doctrine\Common\Collections\ArrayCollection_elements";a:1:{i:0;O:42:"Impression\DemandBundle\Entity\Publication":5:{s:50:"Impression\DemandBundle\Entity\Publicationeditor";s:5:"BREAL";s:53:"Impression\DemandBundle\Entity\Publicationcoauthors";s:5:"MONOT";s:49:"Impression\DemandBundle\Entity\Publicationtitle";s:18:"USA Canada mexique";s:51:"Impression\DemandBundle\Entity\PublicationnbPages";d:150;s:52:"Impression\DemandBundle\Entity\PublicationnbCopies";d:150;}}}
and this gives the error.
For a object add after my upgrade, I have something like this in the database :
O:43:"Doctrine\Common\Collections\ArrayCollection":1:{s:53:"Doctrine\Common\Collections\ArrayCollectionelements";a:1:{i:0;O:42:"Impression\DemandBundle\Entity\Publication":5:{s:50:"Impression\DemandBundle\Entity\Publicationeditor";s:8:"dfg dfgd";s:53:"Impression\DemandBundle\Entity\Publicationcoauthors";s:7:"dfg dfg";s:49:"Impression\DemandBundle\Entity\Publicationtitle";s:5:"fdg d";s:51:"Impression\DemandBundle\Entity\PublicationnbPages";d:5;s:52:"Impression\DemandBundle\Entity\PublicationnbCopies";d:3;}}}
and the function findProtectedPublications() works without errors.
The difference between the two versions is ArrayCollection_elements for the first and ArrayCollectionelements for the second.
To correct this data, I tried with
UPDATE demand SET pub_refs = REPLACE (pub_refs, "ArrayCollection_elements', 'ArrayCollectionelements')
but this doesn't work because of special chars. Trying with
UPDATE demand SET pub_refs = REPLACE (pub_refs, "ArrayCollection�_elements', 'ArrayCollection�elements')
doesn't work better. How can I correct this data ?

Doctrine can populate results as an Array instead of an ArrayCollection, simply change the getResult() call to:
$results = $query->getResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);
This would be the most efficient way to complete your task however you could also use ArrayCollection's built-in toArray() method to convert its own data to array format:
$publications = $results->toArray();

As the problem seems to be due to a change in the storage of ArrayCollection in database between 2.3 and 2.7 version of symfony, I created an line command to update these in database.

Related

Symfony 3 Too many parameters

I'm new to Symfony, and I got an error while running a query :
public function getFilteredArticles($page, $nbPerPage, $data) {
$query = $this->createQueryBuilder('a')
->leftJoin('a.images', 'i')
->addSelect('i')
->leftJoin('a.type_stockage', 't')
->addSelect('t')
->leftJoin('a.famille', 'f')
->addSelect('f');
if ($data['famille'] != '') {
$query->where('f.id = :famille')
->setParameter('famille', $data['famille']);
}
if ($data['rds'] == false) {
$query->where('a.stock_actuel > 0');
}
if ($data['recherche'] != '' && $data['recherche'] != null) {
$query->where('a.ref_article LIKE :recherche')
->setParameter('recherche', '%' . $data['recherche'] . '%');
}
$query->leftJoin('a.sousfamille', 's')
->orderBy('a.ref_article', 'ASC')
->getQuery();
$query->setFirstResult(($page - 1) * $nbPerPage)
->setMaxResults($nbPerPage);
return new Paginator($query, true);
}
This query have conditionnals parameters as you can see, that returns the list of articles I need for a table. But when I run this query to fill my table, I got the error :
An exception has been thrown during the rendering of a template ("Too
many parameters: the query defines 0 parameters and you bound 1").
I don't know why he is expecting 0 parameters. I tried using setParameters instead, but the result is the same.
Does anyone has an idea?
You should use andWhere() methods instead of where().
where() method removes all previous where, but setParameter() does not. That's why he found more parameters than where clauses.
I personally never use where if the condition has no sense to be the first condition, to avoid this kinds of errors.
if ($data['famille'] != '') {
$query->andWhere('f.id = :famille')
->setParameter('famille', $data['famille']);
}
if ($data['rds'] == false) {
$query->andWhere('a.stock_actuel > 0');
}
if ($data['recherche'] != '' && $data['recherche'] != null) {
$query->andWhere('a.ref_article LIKE :recherche')
->setParameter('recherche', '%' . $data['recherche'] . '%');
}
where() php doc
Specifies one or more restrictions to the query result.
Replaces any previously specified restrictions, if any.
andWhere() php doc
Adds one or more restrictions to the query results, forming a logical
conjunction with any previously specified restrictions.
My error, in Symfony 4, using Doctrine 2.6 was
Too many parameters: the query defines 0 parameters and you bound 2
The problem was that I wasn't defining the parameters in andWhere method as
$this->createQueryBuilder('q')
...
->andWhere('q.propertyDate IS NOT NULL') //this also couldn't find anywhere
->andWhere('q.parameterName = :parameterName')
->setParameters(['q.parameterName' => $parameterName, ...2nd parameter])
As I couldn't find any answer to my problem, but was similar to this one, I thought to maybe help someone who is struggling like I was.
also in symfony 5 and 6 you should use andWhere() methods instead of where().
where() method removes all previous where, but setParameter() does not. That's why he found more parameters than where clauses.

Symfony3 Doctrine findByDate filter by month and/or year

I need to query Statistics by month and/or year but I get this error:
Error: Expected known function, got 'YEAR'
My code:
public function findByMonthYear($month, $year)
{
$qb = $this->createQueryBuilder('p')
->where('YEAR(p.date) = :year')
->andWhere('MONTH(p.date) = :month');
$qb->setParameter('year', $year)
->setParameter('month', $month);
return $qb->getQuery()->getOneOrNullResult();
}
With some research it shows that dql doesn't have YEAR() function so it's fare...http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/working-with-datetime.html
In the end, I'm not stick on the solution. So if you've got a clean one for the same result I'll take it as an answer.
A colleague told me that a solution as the following one may works:
where('p.date = :date')
setParameter('date', ''.$year.'-'.$month.'-%') // 2016-07-%
No success so far.
public function findByMonthYear($month, $year)
{
$fromTime = new \DateTime($year . '-' . $month . '-01');
$toTime = new \DateTime($fromTime->format('Y-m-d') . ' first day of next month');
$qb = $this->createQueryBuilder('p')
->where('p.date >= :fromTime')
->andWhere('p.date < :toTime');
->setParameter('fromTime', $fromTime)
->setParameter('toTime', $toTime);
return $qb->getQuery()->getOneOrNullResult();
}

ZF2 Doctrine Query With Multiple OR Conditions

I've wrote the following Doctrine query:
$query3 = $this->entityManager
->createQueryBuilder()
->select('t.textDomain , t.translationKey , t.languageIso , t.translationDate')
->from(
'AMDatabase\Entity\TheVerse\TranslationsMasters',
't'
)
->groupBy('t.languageIso')
->orderBy(
't.translationDate',
'DESC'
);
// the values of $key2 array are:
// en-US
// es-MX
// es-PR
foreach( $translation AS $key2=>$value2 ) {
if ( $key2 == 'en-US' ) {
$query3
->orWhere(
$query3->expr()
->like(
't.languageIso',
':languageIso'
)
)
->setParameter(
'languageIso',
$key2
);
}
}
$result3 = $query3->getQuery()
->getArrayResult();
How do I have the query search for all 3 language ISO's at the same time?
With "if ( $key2 == 'en-US' ) {" the query executes and gives me the expected result.
But if I remove "if ( $key2 == 'en-US' ) {" there are no search results.
I thought by using "orWhere" it would keep adding conditions to the query (where en-US will still produce a match).
In haven't ever been able to get orWhere to function the way I think it should. It might be that you need a Where in your opening definition before you can add an orWhere later. You might have to use the nested orX statement like this instead:
$query3->andWhere($query3->expr()->orX(
$query3->expr()->like('t.languageIso', $query3->expr()->literal('en-US')),
$query3->expr()->like('t.languageIso', $query3->expr()->literal('es-MX')),
$query3->expr()->like('t.languageIso', $query3->expr()->literal('es-PR'))
));
You can't develop the statement through a loop. But, since you've only got three criteria, it's easy enough to write out.

Call to undefined method Slice in Doctrine

I have this function,
public function getWall(){
$q = $this->createQueryBuilder('f');
$q->leftJoin("f.profilo", 'p');
$q->leftJoin("p.utente", 'u');
$q->where('(f.foto_eliminata IS NULL OR f.foto_eliminata != 1)');
$q->andWhere('p.fase_registrazione = :fase');
$q->andWhere('u.locked = :false');
$q->slice(0, 20);
$q->setParameter(':fase', 100);
$q->setParameter('false', false);
$q->orderBy('f.created_at', 'desc');
$dql = $q->getQuery();
$results = $dql->execute();
return $results;
}
but I get this error,
Call to undefined method Doctrine\ORM\QueryBuilder::slice()
Ok, so, u get this error, cause QueryBuilder has no such method. But Collection has. If u want to use slice, a possible variant is:
use Doctrine\Common\Collections;
public function getWall(){
$result = $this->createQueryBuilder('f')
->leftJoin("f.profilo", 'p')
->leftJoin("p.utente", 'u')
->where('(f.foto_eliminata IS NULL OR f.foto_eliminata != 1)')
->andWhere('p.fase_registrazione = :fase')
->andWhere('u.locked = :false')
->setParameter('fase', 100)
->setParameter('false', false)
->orderBy('f.created_at', 'desc')
->getQuery()
->getResult();
// $result typed as array
return new Collections\ArrayCollection($result))->slice(0,20); // convert array to collection, then slice
}
By the way, it is not a good idea to 'limit' result of the query in a such way.
U can use setMaxResults(20), and not to select all objects at all.
About lazy collections (http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/extra-lazy-associations.html): after selecting result objects, u can take some object from result collection: $r = $result[0] after that:
$portfilos = $r->getPortfolio(); // returns for example Collection with some objects;
// its Lazy, without SQL query!
$portfolios->slice(0, 20); // queries first 20 potfolios
To use slice is a rather good idea, if u have lots of objects in some relation.
p.s. sry, mb I didn't recognized your problem, but tried :)
EDITED
fixed errors in code.

AMFPHP working for ArrayCollection in Flex

I have a function in my php class which must receive an array of Objects. In flex, I send the data (as ArrayCollection) calling the service. If I work locally, the PHP receive the data and store all the records in the database, but i I place such service in the server, the function doesnt work.
public function putPrecioBaseProductos($data) {
$priveID = $data[0]->priveID;
$date = $data[0]->date;
$res = mysql_query("DELETE FROM db.prices WHERE priveID=".$priveID." AND date='".$date."'");
if (!$res) return '0';
$cadena = "";
for ($i=0; $i < count($data); $i++) {
if ($cadena != '') $cadena .= ', ';
$cadena .= "(".$priveID.", ".$data[$i]->productID.", '".$data[$i]->precio1."', '".$data[$i]->precio2."', '".$data[$i]->precio3."', '".$data[$i]->precio4."', '".$data[$i]->precio5."', '".$date."')";
}
$res = mysql_query( "INSERT INTO tabo4.precios_base (proveedorID, productoID, precio1, precio2, precio3, precio4, precio5, fecha) VALUES ".$cadena );
if ($res) return '1'; else return '0';
}
I have been googling and found that amfphp do not support ArrayColletion as parameter but as i have just said, locally (using MAMP), data is received as desired but in server not.
Anyone know why?
Thanks.
Try sending data as Array instead of ArrayCollection.
ArrayCollection does not work well with AMFPhp ...
To get the array just use:
myArrayCollection.source;

Resources