P
P
Polim2016-01-28 20:14:19
symfony
Polim, 2016-01-28 20:14:19

How to properly build a query on Doctrine 2 + Symfony 2?

There are 2 tables (table1, table2) between them OneToOne relationship
table1 (id, text);
table2 (id, table1_id, param1, param2, param3)
Parameters come via get-request
As a result, you need to return Entity \ table1 satisfying the request, at the same time, the number of parameters may change

$em=$this->get("doctrine")->getManager();
$get=$request->query;
foreach($get as $key=>$value)
{
  if($value!='')
  // ... //
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
curator, 2016-01-29
@Polim

You can make a OneToOne relationship two-way:

// Entity1, она же table1
/**
 * @OneToOne(targetEntity="Entity2", mappedBy="parent")
 */
private $child;

// Entity2, она же table2
/**
 * @OneToOne(targetEntity="Entity1", inversedBy="child")
 * @JoinColumn(name="table1_id", referencedColumnName="id")
 */
private $parent;

And then:
$getParams = $this->getRequest()->query->all();

$params = array_filter($getParams, function($el) {
    return !empty($el);
});

$queryBuilder = $this->getDoctine()
    ->getRepository('Entity1')
    ->createQueryBuilder('t')
    ->leftJoin('t.child', 'e');

foreach ($params as $key => $val)
{
    $where = sprintf('e.%s = :%s', $key, $key);

    $queryBuilder
        ->andWhere($where)
        ->setParameter($key, $value);
}

$res = $queryBuilder
    ->getQuery()
    ->getResult();

Something like this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question