DELETE query not working in DQL doctrine Symfony2 - symfony

I am to delete a row based on ID, and i used this query to do the task:
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery('DELETE buss from StreetBumbApiBundle:BussOwner buss WHERE buss.id = :bussId')
->setParameter("bussId", $bussId);
$list = $query->getResult();
but i am getting this error:
{
"code": 500,
"message": "[Semantical Error] line 0, col 7 near 'buss from StreetBumbApiBundle:BussOwner': Error: Class 'buss' is not defined."
}
What is wrong i am doing?

You could solve this easily by using the QueryBuilder:
$em = $this->getDoctrine()->getManager();
$qb = $em->createQueryBuilder();
$query = $qb->delete('StreetBumbApiBundle:BussOwner', 'buss')
->where('buss.id = :bussId')
->setParameter('bussId', "bussId")
->getQuery();
$query->execute();
BTW: If you replace getQuery with getDQL you can see how this translates into DQL (or getSQL)
What essentially is wrong in your method is the from in your Delete statement as delete in DQL looks like this:
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'DELETE StreetBumbApiBundle:BussOwner buss
WHERE buss.id = :bussId')
->setParameter("bussId", $bussId);
$query->execute();
Also, I am not sure why you use $query->getResult().
What would be the expected result of a delete? $query->execute(); does the job.
Apart from that, if you don't do complex delete statements, and in your case you are deleting an Entity querying with an Id.
Why not:
$em = $this->getDoctrine()->getManager();
$em->remove($entity);
And therefore pass the Entity, not just the Id to your delete function?

Alternative solution: your DQL is not a good one, try with this
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'DELETE
StreetBumbApiBundle:BussOwner buss
WHERE
buss.id = :bussId'
)
->setParameter("bussId", $bussId);
$result = $query->execute();

Related

DQL query ManyToMany IN

This query in not working. What could be wrong? Post has author(User entity). User has Following(ManyToMany self-directing)
I'm trying to get all Posts of the Users which I'm following
$userId = $this->getUser()->getId();
$qb = $em->createQueryBuilder();
$qb2 = $qb;
$qb2 = $em->createQueryBuilder()
->select('u.following')
->from('AppBundle\Entity\User', 'u')
->where('u.id = :userId');
$qb->select('p')
->from('AppBundle\Entity\Post', 'p')
->where($qb->expr()->In('p.author', $qb2->getDQL()));
$qb->setParameter('userId', $userId);
$dql = $qb->getDQL();
I will assume that your code is in repository as it should be...
src/AppBundle/Controller/PostController.php
$em=$this->getDoctrine()->getManager();
$myResultCollection=$em->getRepository(Post::class)->myCustomQuery($this->getUser());
src/AppBundle/Repository/PostRepository.php
public function myCustomQuery(User $user) {
$em=$this->getEntityManager();
$qb=$em->createQueryBuilder();
return $qb->select("p")
->from(Post::class, "p")
->where($qb->expr()->in("p.author",
$qb->select("u.following")
->from(User::class, "u")
->where("u.id=:USERID")
->getDQL()))
->setParameters(array('USERID'=>$user->getId()))
->getQuery()
->execute();
}
As side note, you should be careful with quotes.
Make sure to use double quotes when using DQL (it's true for SQL too).
The reason is because you need simple quote for strings in queries.

how to use like with findBy in symfony3?

I am using symfony3:
I want use like in my query.
$repository = $this->getDoctrine()->getRepository('AppBundle:ABC');
echo $searchstring = "LIKE '%".$searchtxt."%'"; die;
$res=$repository->findBy(array('fname' => $searchstring));
$normalizer = new ObjectNormalizer();
$encoder = new JsonEncoder();
$serializer = new Serializer(array($normalizer), array($encoder));
$response=$serializer->serialize($res, 'json'); // Output: {"name":"foo","sportsman":false}
return new Response($response);
Its return null
Anyone can suggest me ?
The find*() methods of Doctrine repositories don't allow to perform queries using LIKE for comparison. You need to write a custom DQL query (see Querying for Objects with DQL and Doctrine Query Language):
$query = $em->createQuery("SELECT abc FROM AppBundle:ABC abc WHERE fname LIKE :fname");
$query->setParameter('fname', 'LIKE "%'.$searchtxt.'%"');
$result = $query->getResult();

Retrieve object with nativeQuery in Symfony2

I want retrieve an object with native query in Symfony 2
my code is:
$rsm = new ResultSetMapping($this->getEntityManager());
$rsm->addEntityResult('SNUserBundle:User', 'u');
$rsm->addFieldResult('u', 'nickname', 'nickname');
$query = $this->getEntityManager()->createNativeQuery('SELECT u.nickname FROM u WHERE u.nickname = ?', $rsm);
$query->setParameter(1, 'barno7');
$users = $query->getResult();
I have this error
An exception occurred while executing 'SELECT u.nickname FROM u WHERE u.nickname = ?' with params ["barno7"]:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'sn.u' doesn't exist
my table name sn_user and in my entity SNUserBundle:User have this annotation
* #ORM\Table(name="sn_user")
i try also
$query = $this->getEntityManager()->createNativeQuery('SELECT u.nickname FROM user WHERE u.nickname = ?', $rsm);
and my error is
An exception occurred while executing 'SELECT u.nickname FROM users WHERE u.nickname = ?' with params ["barno7"]:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'sn.user' doesn't exist
my real table is sn_user
I think you are mixing up SQL and DQL, or the functions that use each. It looks like you want to use DQL to query, which will return an object. In that case, you don't use the createNativeQuery method. This method if for SQL.
See the Symfony docs on DQL for an example of how to query with DQL. Here is the example snippet from the docs:
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT p
FROM AcmeStoreBundle:Product p
WHERE p.price > :price
ORDER BY p.price ASC'
)->setParameter('price', '19.99');
$products = $query->getResult();
follow this syntax, and you should be fine.
I resolve like this
$rsm = new ResultSetMapping;
$rsm->addEntityResult('SNUserBundle:User', 'u');
$rsm->addFieldResult('u', 'id', 'id');
$rsm->addFieldResult('u', 'n', 'nickname');
$query = $this->getEntityManager()->createNativeQuery('
SELECT u.id ,u.nickname as n FROM sn_user u WHERE u.nickname LIKE = ?', $rsm);
$query->setParameter(1, 'barno7');
$users = $query->execute();
return $users;

Doctrine2 findOneBy argument equivalent to BETWEEN in SQL

I need to be able to use the following WHERE clause in Doctrine:
WHERE AL.UserID = 41 AND (TheDate BETWEEN DATE_SUB(CURDATE(), INTERVAL 2 WEEK) AND CURDATE())
and what I'm currently doing is:
$results = $em->getRepository('MyBundle:MyTable')->findOneBy(array('userId' => $userId));
However, I haven't been able to filter results by the last 2 weeks without writing SQL or DQL.
Is there any way I can achieve this through Doctrine's methods?
You can use QueryBuilder. Assuming you are using MySQL BETWEEN, something like:
<?php
// $em instanceof EntityManager
$qb = $em->createQueryBuilder();
$now = new DateTime();
$qb->select('c')
->from('MyClass', 'c')
->where($qb->expr()->andX(
$qb->expr()->eq('c.UserID', '?1'),
$qb->expr()->gte('c.TheDate', '?2'),
$qb->expr()->lte('c.TheDate', '?3')
))
->setParameter(1, 41)
->setParameter(2, $now.sub(new DateInterval('P2W')))
->setParameter(3, $now);
$query = $qb->getQuery();
$c = $query->getSingleResult();
This is cleaner code and should work across the different database platforms supported by Doctrine2 ORM.

Use Limit and Offset in Doctrine2 query

I'm trying to do the pagination, but there is an error:
[Syntax Error] line 0, col 57: Error: Expected end of string, got 'limit'
I'm not quite sure if this is the right syntax (and logic) to make my query:
public function getFriendsFromTo ($user, $limit, $offset)
{
return $this->getEntityManager()
->createQuery('SELECT f FROM EMMyFriendsBundle:Friend f WHERE f.user='.$user.' limit '.$limit. 'offset' .$offset)
->getResult();
}
Friends and users are related manyToOne and oneToMany, so in the friends table there is a field - user_id.
This is in my controller:
$user = $this->get('security.context')->getToken()->getUser();
$id = $user->getId();
$friends = $user->getFriends();
$result = count($friends)
$FR_PER_PAGE = 7;
$pages = $result/$FR_PER_PAGE;
$em = $this->getDoctrine()->getEntityManager();
$friends = $em->getRepository('EMMyFriendsBundle:Friend')
->getFriendsFromTo($id, $FR_PER_PAGE, $page*$FR_PER_PAGE);
I know that it's stupid and even wrong (especially the third parameter to be $page*$FR_PER_PAGE), but I just wanted to try if the query works, and it didn't.
Nope. Use:
return $this->getEntityManager()
->createQuery('...')
->setMaxResults(5)
->setFirstResult(10)
->getResult();
$towary = $this->getDoctrine()
->getRepository('AcmeStoreBundle:Towar')
->findBy(array(),array(),10,($current-1)*$numItemsPerPage);
You can use findBy 3rd and 4th parameters of method of doctrine repository, which are limit and offset.
Here is the method definition:
findBy(
array $criteria,
array $orderBy = null,
integer|null $limit = null,
integer|null $offset = null
)
Source: http://www.doctrine-project.org/api/orm/2.2/class-Doctrine.ORM.EntityRepository.html
you can also use
$query->getSingleResult();
Doctrine2.6, stumbled upon this old post and tried the DQL way but it did not fit for purpose. So if you want to avoid using DQL because you already have Entities mapped and joined together, you can do paging using matching & Criteria
$criteria = Criteria::create()
->setMaxResults($limit ? $limit : null)
->setFirstResult($offset ? $offset : null)
$result = $em->getRepository('EMMyFriendsBundle:Friend')
->matching($criteria)->toArray();

Resources