Symfony 2 Doctrine COUNT - php

I have in my table "Artiste" one column "valideAdmin" who takes value 1 or 0.
I try to make a simple count to return the number of entries in my table where "valideAdmin" is to 1:
$repo = $this ->getDoctrine()
->getManager()
->getRepository('ProjectMainBundle:Artiste');
$qb = $repo->createQueryBuilder('valideAdmin');
$qb->select('COUNT(valideAdmin)');
$qb->where('valideAdmin=1');
$count = $qb->getQuery()->getSingleScalarResult();
return array(
'count' => $count
);
But it always "1" who's return...
Without where clause, I have the total count of the entries of the table, but valideAdmin can be 0 or 1. I only want the count number where valideAdmin=1
Thanks for help

createQueryBuilder()'s first parameter is the alias that you want your entity to take (ie.: a short name to be used to refer to your entity in the query).
What you need to do is set a proper alias for your entity (for example a for Artiste) and then COUNT() the instances of your entity where the property (not the column) valideAdmin is set to one:
$repo = $this ->getDoctrine()
->getManager()
->getRepository('ProjectMainBundle:Artiste');
$qb = $repo->createQueryBuilder('a');
$qb->select('COUNT(a)');
$qb->where('a.valideAdmin = :valideAdmin');
$qb->setParameter('valideAdmin', 1);
$count = $qb->getQuery()->getSingleScalarResult();
Remember that DQL runs queries on entities. The DQL your write is then translated into SQL to query the underlying data source after.

Also you can fetch all date then use of COUNT function in PHP
This method has an advantage.You do not have to use a complex query.
You have all the information with count columns
$repositoryArtiste = $this->getDoctrine()
->getRepository('ProjectMainBundle:Artiste');
$queryArtiste= $repositoryArtiste->createQueryBuilder('a')
->Where('a.valideAdmin = :valideAdmin')
->setParameter('valideAdmin',1)
->getQuery();
$Artiste = $queryArtiste->getResult();
var_dump(count($Artiste));

Related

Yii2 How to get all values from column (DB)

I've been sitting for hours trying to find how to get values from table's iab_categories column category_name. I've found only the way to echo all table names:
$connection = Yii::app()->db;//get connection
$dbSchema = $connection->schema;
//or $connection->getSchema();
$tableNames = $dbSchema->getTableNames();//returns array of tbl schema's
var_export($tableNames);
Can anyone help me?
You can use query builder to do that:
$categories = (new \yii\db\Query())
->select(['category_name'])
->from('iab_categories')
->column();
The select() method sets what columns should be included in result.
The from() method sets what table should be queried.
And the column() method executes the query and return first column from result set as array.
EDIT: now, I've realized that even though you've mentioned Yii 2 in title the code you've included in question looks more like Yii 1.x.
So there is query builder version for Yii 1.x:
$categories = Yii::app()->db->createCommand()
->select('category_name')
->from('iab_categories')
->queryColumn();

Symfony 2 - fetch the last inserted row from table

How can I rewrite this code in order to get last inserted record from the table?
$repository = $entityManager->getRepository('AdminBundle:MyTable');
$product = $repository->find($id);
I tried something like
$repository->findBy(array('id','DESC')->setMaxResults(1);
But it did not work for me.
You could get the latest record by using findBy() with order by, limit and offset parameters
$results = $repository->findBy(array(),array('id'=>'DESC'),1,0);
First argument is for filter criteria
Second argument takes order by criteria
Third argument is for limit
Fourth argument sets offset
Note it will return you the results set as array of objects so you can get single object from result as $results[0]
FindBy() Examples
Instead of hacking code where you want to use it, you can also create a repository method and call it when necessary.
/**
* Repository method for finding the newest inserted
* entry inside the database. Will return the latest
* entry when one is existent, otherwise will return
* null.
*
* #return MyTable|null
*/
public function findLastInserted()
{
return $this
->createQueryBuilder("e")
->orderBy("id", "DESC")
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
}
References:
https://symfony.com/doc/current/doctrine.html#querying-for-objects-the-repository
After looking for one I decided to try it myself, I think it was much less verbose:
$myRepository->findOneBy([], ['id' => 'DESC']);
Please try the below one
$repository = $entityManager->getRepository('AdminBundle:MyTable');
$repository->setMaxResults(1)->orderBy('id', 'DESC');
$results = $repository->getQuery()->getSingleResult();
Reference:
https://undebugable.wordpress.com/2016/01/27/symfony2-querybuilder-find-first-and-find-last-record-in-table/
You can add these functions to your repository:
public function getLastRow(): ?YourEntity
{
return $this->findOneBy([], ['id' => 'DESC']);
}
public function getLastId(): int
{
$lastRow = $this->getLastRow();
return $lastRow ? $lastRow->getId() : 0;
}
You can be collected by getting the id of the inserted object
$em->persist($entity);
$em->flush();
$entity->getId();
OR
$entitymanager->getRepository("entity")->findBy([],["id"=>desc])->getId();

Doctrine QueryBuilder: ManyToOne Relationship where more than one subEntity must match

I am trying to do a query where I have an entity Job and an entity JobProperty where 1 Job can have many JobProperties.
Query on a many-to-many relationship using Doctrine with Symfony2 explains how to retrieve matches on one entity based on values of it's subEntities. From this I have built the query:
$qb = $this->getDoctrine()->getRepository('AppBundle:Job')->createQueryBuilder('job')
->innerJoin('job.properties','property');
foreach($filters as $label => $value)
{
$qb->andWhere('property.label = :label AND property.value = :value')
->setParameter('label',$label)
->setParameter('value',$value);
}
The query above works to an extent, but it provides results where a property matches against ANY of the filters, and does not only provide results where ALL filters are matched. I need it to return only results where ALL filters are matched.
I might have to go about this in a different way, but I'm not sure I would implement.
You are not doing it correctly you are matching labels and values with the last filter values because the placeholders :label , :value used in query are not unique for each loop iteration, so all the clauses generated by loop will match with the last label and value.
To get the jobs whose each property match with the provided filters you can write somewhat like below doctrine query.
First it will collect all labels and values in separate array and then it will match with properties of job by using IN() operation, in last to get the jobs whose properties matches all the filters you need to build aggregation to count the matching results and should be equal to the count of filters
$qb = $this->getDoctrine()
->getRepository('AppBundle:Job')
->createQueryBuilder('job')
->innerJoin('job.properties','p');
$labels = array();
$values = array();
foreach($filters as $label => $value)
{
$labels[] = $label;
$values[] = $value;
}
$qb->addSelect('COUNT(DISTINCT p.id) AS total_properties')
->andWhere('p.label IN (:labels)')
->andWhere('p.value IN (:values)')
->addGroupBy('job.id')
->having('total_properties = '.count($filters))
->setParameter('labels',$labels)
->setParameter('values',$values)
->getQuery()
->getResult();
Here is another answer as a reference here which is similar to your question
Symfony2 - Doctrine2 QueryBuilder WHERE IN ManyToMany field

Adding a Having Clause to Doctrine Statement

I am new to Doctrine and I am trying to figure out how to add a having clause on my statement. Basically I want to be able to filter down on items returned based on how many attributes the user selects. The code is as follows:
// create query builder
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('p')
->from($this->_entityName, 'p')
->leftJoin('p.options', 'o')
->where('p.active = :active')
->setParameter('active', 1);
// add filters
$qb->leftJoin('o.attributes', 'a');
$ands = array();
foreach ($value as $id => $values)
{ echo count($values);
$ands[] = $qb->expr()->andX(
$qb->expr()->eq('a.attribute_id', intval($id)),
$qb->expr()->in('a.attribute_value_id', array_map('intval', $values))
$qb->having('COUNT(*)=3) // THIS DOESN'T WORK
//$qb->expr()->having('COUNT(*)=3) // THIS DOESN'T WORK EITHER
);
}
$where = $qb->expr()->andX();
foreach ($ands as $and)
{
$where->add($and);
}
$qb->andWhere($where);
$result = $qb->getQuery()->getResult();
return $result;
When I try to execute the statement with the having() clause I get this error:
Expression of type 'Doctrine\ORM\QueryBuilder' not allowed in this context.
Without the having() clause everything works perfectly.
I have no idea how to solve this.
HAVING clause requires a GROUP BY. In doctrine it would be something like that:
$qb->groupBy('p.id'); // or use an appropriate field
$qb->having('COUNT(*) = :some_count');
$qb->setParameter('some_count', 3);
Assuming you're using mysql, here is a having clause tutorial: http://www.mysqltutorial.org/mysql-having.aspx
Perhaps you should bind number 3 to a parameter:
$qb->having('COUNT(*)=:some_count')
$qb->setParameter('some_count',3)
Goal: filter down The one side where we have some known summable conditions we want to filter by (e.g., the count of Original Parts in a Bundle) on the many side of a O2M relationship wehere want to limit the One side along with some other criteria to select on.
We are then adding in a few conditions for the LEFT_JOIN operation:
Condition #1 - the bundle.id == the original_part.bundle ID.
Condition #2 - The original_part's partStatusType == 3 (some hard-coded value).
Then we filter down to the COUNT(op) >= 1 which gives our more limited response that works just fine with pagination.
$qb->leftJoin(OriginalPart::class, 'op', Expr\Join::WITH,
$qb->expr()->andX(
$qb->expr()->eq('op.bundle', 'row.id'),
$qb->expr()->eq('op.partStatusType', 3)));
$qb->groupBy('row.id');
$qb->having($qb->expr()->gte('COUNT(op)', 1));
row is the alias for the One (bundle entity).

Get single row result with Doctrine NativeQuery

I'm trying to get a single row returned from a native query with Doctrine. Here's my code:
$rsm = new ResultSetMapping;
$rsm->addEntityResult('VNNCoreBundle:Player', 'p');
$rsm->addFieldResult('p', 'player_id', 'id');
$sql = "
SELECT player_id
FROM players p
WHERE CONCAT(p.first_name, ' ', p.last_name) = ?
";
$query = $this->getEntityManager()->createNativeQuery($sql, $rsm);
$query->setParameter(1, $name);
$players = $query->getResult();
That last line returns a list of players but I just want one result. How do I do that?
You can use $query->getSingleResult(), which will throw an exception if more than one result are found, or if no result is found. (see the related phpdoc here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L791)
There's also the less famous $query->getOneOrNullResult() which will throw an exception if more than one result are found, and return null if no result is found. (see the related phpdoc here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L752)
Both getSingleResult() and getOneOrNullResult() will throw an exception if there is more than one result.
To fix this problem you could add setMaxResults(1) to your query builder.
$firstSubscriber = $entity->createQueryBuilder()->select('sub')
->from("\Application\Entity\Subscriber", 'sub')
->where('sub.subscribe=:isSubscribe')
->setParameter('isSubscribe', 1)
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
->getSingleScalarResult() will return a single value, instead of an array.
I just want one result
implies that you expect only one row to be returned. So either adapt your query, e.g.
SELECT player_id
FROM players p
WHERE CONCAT(p.first_name, ' ', p.last_name) = ?
LIMIT 0, 1
(and then use getSingleResult() as recommended by AdrienBrault) or fetch rows as an array and access the first item:
// ...
$players = $query->getArrayResult();
$myPlayer = $players[0];
I use fetchObject() here a small example using Symfony 4.4
<?php
use Doctrine\DBAL\Driver\Connection;
class MyController{
public function index($username){
$queryBuilder = $connection->createQueryBuilder();
$queryBuilder
->select('id', 'name')
->from('app_user')
->where('name = ?')
->setParameter(0, $username)
->setMaxResults(1);
$stmUser = $queryBuilder->execute();
dump($stmUser->fetchObject());
//get_class_methods($stmUser) -> to see all methods
}
}
Response:
{
"id": "2", "name":"myuser"
}
To fetch single row
$result = $this->getEntityManager()->getConnection()->fetchAssoc($sql)
To fetch all records
$result = $this->getEntityManager()->getConnection()->fetchAll($sql)
Here you can use sql native query, all will work without any issue.

Categories