Doctrine use count() in NativeQuery with ResultSetMapping - doctrine-orm

i try to use NativeQuery of Doctrine. If i use my SQL ind Phpmyadmin i have the good result. If i use this, my var_dump return an empty array. I don't understand why.
$sql = 'SELECT COUNT(id) as nb FROM app_facture f WHERE SUBSTR(f.datecreate_facture, 1, 4) = 2014 AND SUBSTR(f.numero_facture,1,1) != "E"';
$rsm = new ResultSetMapping;
$rsm->addEntityResult('Acme\MyBundle\Entity\Facture', 'f');
$rsm->addFieldResult('f', 'COUNT(id)', 'nb');
$query = $this->getEntityManager()->createNativeQuery($sql,$rsm);
$results = $query->getResult();
var_dump($results);//return empty array
Thanks

Try
$rsm->addFieldResult('f', 'nb', 'id');
this worked for me.

Related

Doctrine query builder - nested queries

How can I convert this query into symfony 2 doctrine query builder?
SELECT
artist_id,
DATE,
balance,
TYPE
FROM TRANSACTION AS
t1
WHERE
DATE =(
SELECT
MAX(DATE)
FROM TRANSACTION
WHERE
artist_id = t1.artist_id AND
STATUS
IN(
'partial',
'pending',
'deducted',
'accepted'
) AND TYPE NOT LIKE 'payment'
)
GROUP BY
artist_id
ORDER BY
artist_id
I tried the following:
$qb = $this->getEntityManager()->createQueryBuilder()
->select('t.balance','a.id','t.date')
->from('TestMainBundle:Transaction','t')
->Join('t.artist','a')
->where("t.status in ('partial','pending','deducted','accepted')")
->andWhere("t.type NOT LIKE 'payment'")
->groupBy('a.id')
->orderBy('a.id');
return $qb->getQuery()->getResult();
But I am stuck with including the condition of max (date) as well. Any help on this is very much appreciated.
Your Doctrine query will look something like this,
$qb1 = $this->getDoctrine()->getManager()->createQueryBuilder();
$select = $qb1->select('MAX(date) AS max_data')
->from('YourBundle:Transaction', 's')
->where('s.artist_id = :ti_artist_id')
->andWhere('s.status IN (:statuses)')
->andWhere('s.type NOT LIKE :type')
->getQuery();
$qb2 = $this->getDoctrine()->getManager()->createQueryBuilder();
$result = $qb2->select('t.artist_id', 't.date', 't.balance', 't.type')
->from('YourBundle:Transaction', 't');
$result->where($qb2->expr()->eq('t.date', $select->getDQL()))
->setParameter('ti_artist_id', 't.id')
->setParameter('statuses', array('partial','pending','deducted','accepted'))
->setParameter('type', 'payment') //possibly '%payment%'
->orderBy('t.artist_id')
->getQuery()
->getResult();
Cheers!!!

Doctrine2 DQL Syntax error when ordering by count

This is Doctrine Repository function
public function mostReadArticleByUser($userId){
$total = $this->createQueryBuilder('ar')
->select('ar.articleId', 'COUNT(ar)')
->where('ar.authorId = :userId')
->groupBy('ar.articleId')
->orderBy('COUNT(ar)', 'DESC')
->setMaxResults(1)
->setParameter('userId', $userId)
->getQuery()
->getResult();
return $total;
}
which should be equivalent to this query
SELECT article_id, count(id)
FROM profile_article_reads
WHERE author_id = 2
GROUP BY article_id
Order by count(id) DESC
LIMIT 1;
When I execute this code I get error
Error: Expected end of string, got '('
QueryException: SELECT ar.articleId, COUNT(ar) FROM
SciProfileBundle\Entity\ProfileArticleReads ar WHERE ar.authorId =
:userId GROUP BY ar.articleId ORDER BY COUNT(ar) DESC
THe count funtion accept a field, so try with
COUNT(ar.id)
instead of:
COUNT(ar)
Probably for sorting is better using an alias, as example:
public function mostReadArticleByUser($userId){
$total = $this->createQueryBuilder('ar')
->select('ar.articleId', 'COUNT(ar.id) as total')
->where('ar.authorId = :userId')
->groupBy('ar.articleId')
->orderBy('total', 'DESC')
->setMaxResults(1)
->setParameter('userId', $userId)
->getQuery()
->getResult();
return $total;
}
Hope this help

Doctrine 2 how to increment a column for multiple rows at once?

i'm looking for a way to increment a value for multiple rows at once without looping , is it possible in doctrine ?
here is the query in simple sql :
$sql = "UPDATE table set compteur = compteur + 1 where id in ('1','2','3') ";
using doctrine for updating many rows ( not incrementing ) , i have this :
$qb = $this->getEntityManager()->createQueryBuilder();
$query = $qb->update('Application\Entity\Table', 'l')
->set('l.compteur', $qb->expr()->literal('8'))
->where("l.id in ('$ids')")
->getQuery();
$retour = $query->execute();
Thanks for any idea !!
Use DQL for this:
$this->getEntityManager()->createQuery('
UPDATE Application\Entity\Table t
SET t.compteur = t.compteur + 1
')
->execute();
http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/batch-processing.html#dql-update
You can also do it with the querybuilder like so:
$qb->set('l.compteur', $qb->expr()->sum('l.compteur', 1));

Doctrine 2: how do you use a subquery column (in the SELECT clause)

I'm trying to do a simple select query with a subquery in the SELECT clause and have simply not found a way to do it. I've tried with both DQL and with the QueryBuilder, neither work. The code follows, please don't say I could just use a join, this is a simplified example just to illustrate the problem, I have legitimate use cases for subqueries.
// With QueryBuilder
$query = $qb->select(array('a',
'(SELECT at.addresstypeName
FROM e:Addresstype at
WHERE at.addresstypeId = a.addresstypeId
) AS addresstypeName'))
->from('e:Address', 'a')
->where('a.addressId = :addressId')
->setParameter('addressId', 1);
// With DQL
$dql = "SELECT a,
(SELECT at.addresstypeName
FROM e:Addresstype at
WHERE at.addresstypeId = a.addresstypeId
) AS addresstypeName
FROM e:Address a
WHERE a.addressId = :addressId";
$query = $em->createQuery($dql)->setParameter(':addressId', 1);
The following relationship is defined on the Address table:
/**
* #ORM\ManyToOne(targetEntity="Addresstype")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="addresstype_id", referencedColumnName="addresstype_id")
* })
*/
protected $addresstype;
In native SQL, the query would look like this:
SELECT
a.*,
(
SELECT at.addresstype_name
FROM addresstype at
WHERE at.addresstype_id = a.addresstype_id
) AS addresstype_name
FROM address a
WHERE a.address_id = 1
Any ideas?
$query = $qb->select('a')
->addSelect('(SELECT at.addresstypeName
FROM e:Addresstype at
WHERE at.addresstypeId = a.addresstypeId) AS addresstypeName'
)
->from('e:Address', 'a')
->where('a.addressId = :addressId')
->setParameter('addressId', 1);
For me subquery with doctrine works with this query :
$qb->select('e.field')
->addSelect('(SELECT count(mv.nm)
FROM Clt\Bundle\MyBundle\Entity\MV mv
LEFT JOIN Clt\Bundle\MyBundle\Entity\M ma WITH mv.nm=ma.nm
WHERE mv.ne=e.ne and ma.nm is null
) AS nm'
)
->from($this->_entityName, 'e')
->leftJoin('e.m', 'm')
->where($qb->expr()->eq('t.id'.$typeModule, $idElementModule));
Note that in the left join you must use WITH instead of ON...
I know this is an old question, but if you want, you could have used another query builder as your subquery:
$qb->select("a")
->addSelect("(" . $qb2->select("at.addresstypeName")
->from("e:Addresstype", "at")
->where("at.addresstypeId = a.addresstypeId")
->getDQL() . ") AS addresstypeName"
)
->from('e:Address', 'a')
->where('a.addressId = :addressId')
->setParameter('addressId', 1);
In my scenario what I needed was to look into a join and find an Id and use it as boolean, found 1 otherwise 0, then applying this to orderBy. DQL expressions worked only when combined with Where clause, which wasn't my case. So, a DQL subselect saved me.
Adapted more or less to your scenario, it would look like this:
// With QueryBuilder
// In AddressRepository
// Where one address may belong to several addressTypes
public function getWithType($addressType){
$qb = $this->createQueryBuilder('a1');
$qb->addSelect('a1.someField', 'a1.otherField')
$qb->addSelect(
'(SELECT at.addressTypeName
FROM App\Entity\Address a2
JOIN a2.addressType at
WHERE at.id = '.$addressType.' AND a2.id = a1.id
) AS addressTypeName')
//The rest part of the query
}

Collection#Matching an Association in Doctrine

I want to use Collection#Matching against associated objects, but it isn't working. Doing some digging it looks like Doctrine does an in_array call against the two values. The needle is a Persisted Collection (my association) and the haystack is an array of the entities I want to match. Because the needle is a Persisted Collection, the match fails.
Is this possibly a bug or are associations not supported? If they're not supported, is there a work around?
Example:
$query = $em->createQuery("SELECT c FROM Entity\BidCategory c WHERE c.code IN(:categories)");
$query->setParameter('categories', array('CATEGORY_1', 'CATEGORY_2'));
$my_categories = $query->getResult();
$criteria = array(
"min_pub_date" => "01-07-2012",
"max_pub_date" => "01-08-2012"
);
$query = $em->createQuery("SELECT b From Entity\Bid b JOIN b.categories c WHERE b.pub_date > :min_pub_date AND b.pub_date < :max_pub_date");
$query->setParameter("min_pub_date", new DateTime($criteria['min_pub_date']));
$query->setParameter("max_pub_date", new DateTime($criteria['max_pub_date']));
$query->setMaxResults(1);
$bids = $query->getResult();
$criteria = Criteria::create()
->where(Criteria::expr()->in("categories", $my_categories));
$collection = new Doctrine\Common\Collections\ArrayCollection();
foreach($bids as $bid)
{
$collection->add($bid);
}
$matched_bids = $collection->matching($criteria);
The Criteria feature doesn't support associations. The Criteria::expr()->in() method is for regular arrays.