user6533866 user6533866 - 1 month ago 14
Twig Question

Get the last value of a entity field with condition

I'm making a website for performance monitoring.

I have 2 tables:


  • Users table linked in one-to-Many with performances

  • Performances table linked in Many-to-one with users table



I just wanna get the last weight which is not null in my table performances and display it in twig

database screenshot
For exemple in this database, the result would be : 80

I tried with queries but I get an arror message so I don't know how to do
Thanks in advance for your help !

Answer

I hope this could helps you. I suppose you have a repository class for your Performance entity. I would use this kind of code for a Symfony3 application

<?php

namespace AppBundle\Repository; //replace AppBundle by the name of your bundle

use Doctrine\ORM\Tools\Pagination\Paginator;

/**
 * PerformanceRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PerformanceRepository extends \Doctrine\ORM\EntityRepository
{

    public function getLastWeigth()
    {
       $qb = $this->getEntityManager()->createQueryBuilder()
            ->select('p')
            ->from($this->_entityName, 'p')
            ->expr()->isNotNull('p.weight')
            ->orderBy('p.date', 'desc') 
            ->setMaxResults(1);
       $query = $qb->getQuery();
       $result = $query->getSingleResult();

       return $result;
    }
}

Edit: here is an Exemple of use in the controller in a Symfony 3 application:

<?php
namespace AppBundle\Controller\Performance;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use AppBundle\Repository\PerformanceRepository;

class PerformanceController extends Controller
{

    public function lastWeightAction()
    {
        $repo = $this->getDoctrine()->getManager()->getRepository('AppBundle:Performance');
        $lastPerformance = $repo->getLastWeigth();

        //some other code
    }
}

Edit2: If you need to get the last weight by a user Id:

class PerformanceRepository extends \Doctrine\ORM\EntityRepository
{

    public function getLastWeigth($userId)
    {
       $qb = $this->getEntityManager()->createQueryBuilder()
            ->select('p')
            ->from($this->_entityName, 'p')
            ->join('p.user', 'u')
            ->where('u.id = :userId')
            ->expr()->isNotNull('p.weight')
            ->orderBy('p.date', 'desc') 
            ->setMaxResults(1);
            ->setParameter(':userId', $userId);
       $query = $qb->getQuery();
       $result = $query->getSingleResult();

       return $result;
    }
}
Comments