doctrine how to fetch database switch a datetime - symfony

I can't find the answer in the documentation.
I use symfony for an application, i have a database with a datetime for each of my table and would like to get only the row with the most recent datetime is there a function like $repository->findOneById($id) to obtain this object ?

Here is a solution using QueryBuilder:
$repository = $this->getDoctrine()
->getRepository('AcmeStoreBundle:Product');
$query = $repository->createQueryBuilder('p')
->orderBy('p.datetime', 'DESC')
->setMaxResults(1)
->getQuery();
$product = $query->getResult();
Regards.

Related

Symfony QueryBuilder andWhere for User-Relation not Working

I want to load items for a given User. Between Item and User lives a One-To-Many relationship.
If I use the following, everything is working well:
$result = $em→getRepository(Item::class)→findBy(['user' => $user]);
The $result has 3 entries.
Now I have to give additional conditions to the query. So I want to use the queryBuilder insight the repository:
$result = $this->createQueryBuilder('i')
->andWhere('i.user = :user')
->setParameter('user', $user)
->getQuery()
->getResult();
The result is empty but the query runs without any errors.
Can someone tell me what I'm doing wrong?
In both cases the $user is the related App\Entity\User entity.
I found the solution. It didn't work because of the Uuid. This works:
$result = $this->createQueryBuilder('i')
->andWhere('i.user = :user')
->setParameter('user', $user->getId()->toBinary())
->getQuery()
->getResult();

Symfony4 How to get objects with query builder

(Hi!),
I need to get objects from a query builder, but I collect an array, so I have the following error:
Call to a member function getPropertyName() on array
So I suppose than my request isn't correct, but I don't know how to resolve my problem
public function findByYear($year): array
{
$conn = $this->getEntityManager()->getConnection();
$sql = 'SELECT * FROM rent_release r WHERE YEAR(`date`) = :yearRequested';
$stmt = $conn->prepare($sql);
$stmt->execute(['yearRequested' => $year]);
return $stmt->fetchAll();
}
Waiting for your help, thanks :)
Ok so, according to comments, I used createQueryBuilder and beberlei/doctrineextensions.
here is the DQL:
$qb = $this->createQueryBuilder('rr')
->andWhere('YEAR(rr.date) = :year')
->setParameter('year', $year)
->orderBy('rr.date', 'ASC')
->getQuery();
return $qb->execute();
and in doctrine.yaml I added this:
dql:
string_functions:
YEAR: DoctrineExtensions\Query\Mysql\Year
and now it works well, thanks all !

How to find all questions without any answers with Symfony 2?

I have two entities Question and Answer with appropriate relationships.
I want an optimized way (less resource) to find all questions (only id and title) without answers with doctrine.
Thanks for your answer.
In your controller…
Using the QueryBuilder:
$repository = $this->getDoctrine()->getRepository('AcmeStoreBundle:Question');
$qb = $repository->createQueryBuilder('Question');
$query = $qb
->select('DISTINCT Question.id, Question.title')
->leftJoin('Question.answers', 'Answer', $qb->expr()->isNull('Answer.id'))
->getQuery();
$questions = $query->getArrayResult();
Or DQL (partial objects:
$query = $em->createQuery("select partial Question.{id,title}
from MyApp\Domain\Question Question
left join Question.answers Answer
where Answer.id is NULL");
$questions = $query->getResult();
The query builder will return an array while the DQL will return partial objects.
See:
http://docs.doctrine-project.org/en/latest/reference/query-builder.html
http://docs.doctrine-project.org/en/latest/reference/partial-objects.html

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