-5

In Symfony I'm using default ORM Doctrine, but this tool can't give me enough methods to manipulate with different cases. I want to write my own classes and using something like DBAL, just for connections making custom SQL queries and fetch the result. Who can give me some examples? Which classes I should use to make my model layer, extend my functionality.

madberdin
  • 47
  • 8

2 Answers2

0

If you want to write your own SQL query with doctrine you can check that doc page: http://doctrine-orm.readthedocs.org/en/latest/reference/native-sql.html

but most of the time DQL is more than enough

this is from a project I did, ignore my sql query

//Daily Alerts
$dailyAlertsQuery = $em
        ->createQuery("
            SELECT COUNT (a) AS daily
            FROM XXX\xxxBundle\Entity\Alert a
            JOIN a.user u
            WHERE a.mentionUpdate = '1'
            AND u.isActive = '1'
            ")
        ->getResult();

$dailyAlerts = new ArrayCollection($dailyAlertsQuery);
thesearentthedroids
  • 588
  • 1
  • 7
  • 24
  • So I can write my own model classes and use it in my controllers, without use SQL code directly in controllers. Because Symfony by default doesn't exists model like definition. – madberdin Sep 09 '14 at 08:51
0

As a good practise, you may put all your custom queries (SQL or DQL) in an EntityRepository

Here is an example of a custom EntityRepository

use Doctrine\ORM\EntityRepository;
use \Doctrine\Common\Collections\Criteria;

/**
 * RequestRepository
 *
 */
class RequestRepository extends EntityRepository
{

    public function findByStatus($status = array(), $limit = 5, $orderBy = null)
    {
        $queryBuilder = $this->_em->createQueryBuilder();
        $queryBuilder
        ->select('n')
        ->from('BaseBundle:Request', 'n')
        ->where('n.status IN (:status)')
        ->setParameter('status', $status)
        ->setMaxResults($limit);
        if (!is_null($orderBy)) {
            $queryBuilder->orderBy('n.' . $orderBy[0], $orderBy[1]);
        }

        $lines = array();
        foreach ($queryBuilder->getQuery()->getResult() as $line) {
            $lines[] = $line;
        }
        return $lines;
    }

    public function getByExpressions($expressions = array(), $limit = 5, $orderBy = null)
    {
        $criteria = Criteria::create();
        if (!empty($expressions)) {
            foreach ($expressions as $expression) {
                $criteria->andWhere($expression);
            }
        }
        $criteria->setMaxResults($limit);
        if (!is_null($orderBy)) {
            $criteria->orderBy($orderBy);
        }
        return $this->matching($criteria);
    }
}

And in the Entity code, you define this custom repository as follows:

use Doctrine\ORM\Mapping as ORM;

/**
 * Request
 *
 * @ORM\Table(name="request")
 * @ORM\Entity(repositoryClass="BaseBundle\Repository\RequestRepository")
 */
class Request
{
//Entity code, irrelevant here
}
ilyes kooli
  • 11,959
  • 14
  • 50
  • 79