How to delete from database with queryBuilder? - php

I want to delete some data and return the number of the deleting.
This is my code :
public function deleteMyData() : ?int
{
$qb = $this->connection->createQueryBuilder()
->delete('myTable')
->where('pays ="us"')
;
return $qb->execute()->rowCount();
}
I already tested other things like :
->delete()
->from('myTable')
->where('pays ="fr"')
When I run my code I've got this error :
[Symfony\Component\Debug\Exception\FatalThrowableError]
Call to a member function rowCount() on integer
I dumped $qb->execute()->rowCount() and it return "0".
Thanks for your help !
PS : I think that the problem isn't the query because :
Error An exception occurred while executing 'DELETE FROM theQueryTest WHERE pays ="us"':
The SQL is great
PS 2 : I can't use ->getQuery()

This code returns an integer
return $qb->execute();
If you want to count row affected try this:
$qb = $this->createQueryBuilder();
//query
$count = $qb->getQuery()->getSingleScalarResult();

I found the solution
In my case, I have to use $this->connection HOWEVER I don't have to use $qb->execute()
I read the doc and I found this in Connection.php (->delete(...)) :
#return integer The number of affected rows.
So I have to use directly $this->connection->delete(...)
public function deleteMyData() : ?int
{
$qb = $this->connection
->delete('myTable', ['pays' => '"us"'])
;
return $qb;
}

Related

How to fix Call to a member function where() on int

I have to update some records but it doesn't work properly.
Someone know what to do?
$dog = DB::table('dogs')
->update($data)
->where('id', $id);
return response()->json($dog);
})
Call where before update, e.g. :
$dog = DB::table('dogs')->where('id', $id)->update($data);

How to make an Where In subquery in symfony

I'm trying to do this SQL query with Doctrine QueryBuilder:
SELECT * FROM events WHERE NOT id in (SELECT event_id FROM ues WHERE user_id = $userID)
The UserEventStatus has foreign keys from User and event, as well as an integer for status.
I now want to query all events that dont have an entry in UserEventStatus from an particular User.
My function for this in the EventRepository looks like this:
public function getUnReactedEvents(int $userID){
$expr = $this->getEntityManager()->getExpressionBuilder();
$originalQuery = $this->createQueryBuilder('e');
$subquery= $this->createQueryBuilder('b');
$originalQuery->where(
$expr->not(
$expr->in(
'e.id',
$subquery
->select('ues.user')
->from('App/Entity/UserEventStatus', "ues")
->where(
$expr->eq('ues.user', $userID)
)
)
)
);
return $originalQuery->getQuery()->getResult();
}
But i get an error that says:
Error: Method Doctrine\Common\Collections\ArrayCollection::__toString() must not throw an exception, caught ErrorException: Catchable Fatal Error: Object of class Doctrine\ORM\EntityManager could not be converted to string (500 Internal Server Error)
Can anyone help me or point me to right point in the docs? Cause i failed to find something that describes my problem.
And another thing is, that I don't know if its possible, but it would be nice. Can I somehow make direct Object requests? I mean not with the string App/Entity/UserEventStatus but with something like UserEventStatus::class or something.
Thanks for your help in advance. :)
EDIT: It has to be $originalQuery->getQuery()->getResult() of course.
If its like it was with $subquery instead i recive [Semantical Error] line I0, col 41 near 'App/Entity/UserEventStatus': Error: Class 'App' is not defined. (500 Internal Server Error)
Second EDIT:
$expr = $this->getEntityManager()->getExpressionBuilder();
$queryBuilder = $this->createQueryBuilder('e');
$subquery= $this->createQueryBuilder('b')
->select('ues.user')
->from('UserEventStatus', "ues")
->add('where', $expr->eq('ues.user', $userID));
$originalQueryExpression = $expr->not($expr->in('e.id', $subquery));
$queryBuilder->add('where', $originalQueryExpression);
return $queryBuilder->getQuery()->getResult();
Third EDIT: Thanks to #Dilek I made it work with a JOIN. This is the final Query:
$queryBuilder = $this->createQueryBuilder('e')
->leftJoin('App\Entity\UserEventStatus', 'ues', 'WITH', 'ues.user=:userID')
->setParameter('userID', $userID)
->where($expr->orX($expr->not(
$expr->eq('e.id','ues.event')
),
$expr->not($expr->eq('ues.user', $userID)))
);
return $queryBuilder->getQuery()->getResult();
Building AND WHERE into a Query
public function search($term)
{
return $this->createQueryBuilder('cat')
->andWhere('cat.name = :searchTerm')
->setParameter('searchTerm', $term)
->getQuery()
->execute();
}
simple is: ->where('cat.name = :searchTerm')
UPDATE :
I think you need to use where in
$qb->add('where', $qb->expr()->in('ues.user', $userID));
And WHERE Or WHERE

MySQL request return null Controller PHP

I've create a table order on my code, My idea is to generate an Unique order Id per user.
On my controller I have a code with the MYSQL request, and a function to return the result (which works on other SQL requests).
So My idea is on MySQL request is to count the number of order with the same number and If result is =1 I have to generate a new order number. On my order class I have this function:
public static function getCountOrderIfExist($bdd, $order_number) {
$requete = "SELECT * FROM Order WHERE order_number='$order_number'";
$commandes = getResultatRequete($bdd, $requete);
return !empty($commandes) ? $commandes : null;
}
And I call it on my Controller:
$count = Order::getCountOrderIfExist($bdd, $order_number);
while ($count >= 1) {
$order_number= $user_role."_".$user->getUtilisateurId().rand(1,99999)."_".$user->getEntreprise()->getId().rand(1,999999);
}
And here is the code of my getResultatRequete:
function getResultatsRequete(PDO $bdd, $requete) {
$reponse_requete = $bdd->query($requete);
if ($reponse_requete != false) {
$resultat_requete = $reponse_requete->fetchAll();
return str_replace("\\", "", $resultat_requete);
} else {
printErrorInfo($bdd, $requete, true);
return array();
}
}
When I run my code on debug mode the SQL request return NULL and I don't understand why, because when I run my Request on a terminal it works well. Any idea?
From our correspondence in the comments, it seems that the problem lies in the return statement:
return !empty($commandes) ? $commandes : null;
That statement returns any found records, or null if no records are found. However, it seems that the controller expects the function to return the number of matching records (0 if none are found).
In order to return a number for you to work with, you need to instead do a count of the returned records:
return count($commandes);
This should give you the results you need.

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();

How to set a limit in delete query?

I try to delete some data with Doctrine\DBAL\Connection, I want to delete the duplicate data so I have to delete n-1 data (If n data are the same).
public function deleteDuplicateData(array $data) : bool
{
$qb = $this->connection->createQueryBuilder();
$qb->delete('myTable')
->where('id= :id')
->setParameter('id', $data['id'])
->setMaxResults($data['n']-1)
;
return $qb->execute();
}
However the ->setMaxResults($data['n']-1) doesn't work, when I run my code all data are deleted. I tried this ->setMaxResults($data['n']-1) but it does'nt work so I think the method ->setMaxResults() doesn't work for the delete method.
I cant comment, so sry for this ^^
Is it possible to count the rows with duplicate data in your DB System + Do they have the same ID? If yes, you could store the ammount - 1 to a variable $duplicatedRows and use a for loop like:
for($i;$<=$duplicatedRow;$i++){
//Your Code to delete something
}
setMaxResults works only in some cases. It seems to ignore it if it's not managed.
check the Doctrine doc : https://www.doctrine-project.org/projects/doctrine1/en/latest/manual/dql-doctrine-query-language.html#driver-portability
use below function for set limit
public function deleteDuplicateData(array $data) : bool
{
$limit = 10;
$qb = $this->connection->createQueryBuilder();
$qb->delete('myTable')
->where('id= :id')
->setParameter('client_id', $data['id'])
->setMaxResults($limit);
return $qb->execute();
}

Categories