Retrieve object with nativeQuery in Symfony2 - symfony

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;

Related

How to execute a pre-saved dql string

let's say for some reason I have a DQL string saved somewhere (in the DB) along with the necessary parameters, can I set it in a queryBuilder object and execute it?
I expected to be able to so something like
$builder = $entityManager->createQueryBuilder();
$query = $builder->getQuery()
->setDQL($stringDql)
->setParameters($arrayParams);
return $query->iterate();
The Entity manager has ::createQuery(string $dql); Where there string of DQL comes from it would not care.
$dql = 'SELECT u FROM MyProject\Model\User u WHERE u.age > 20';
// $dql = $this->getQueryFromDatabase();
$query = $em->createQuery($dql);

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

DELETE query not working in DQL doctrine Symfony2

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

Doctrine - how select fields to return from the query (in Symfony2)

So imagine a basic query:
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT x FROM MyBundle:MyEntity x'
);
$result = $query->getResult();
How do I select which fields to return? I was a bit thrown at the SELECT part as this is very different from SQL's SELECT (fields) from table. In fact it looks a bit odd to me, why not just do this similar to SQL?
SELECT field1, field2 FROM MyBundle:MyEntity
Anyway, how would I limit to a set list of fields?
You have to use Doctrine partial object:
$q = $em->createQuery("select partial u.{id,name} from MyApp\Domain\User u");

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