Criteria query with contains expression in the Manytoone entity field

Asked

Viewed 97 times

1

Considering the two entities below:

/**
 * @ORM\Table(name="cliente")
 * @ORM\Entity
 */
class Cliente {
    /**
     * @ORM\Column(name="id_cliente", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
    /**
     * @ORM\Column(type="string", length=50)
     */
    private $nome;
    // getters, setters, etc...
}

/**
 * @ORM\Table(name="pedido")
 * @ORM\Entity
 */
class Pedido {
    /**
     * @ORM\Column(name="id_pedido", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
    /**
     * @ORM\ManyToOne(targetEntity="Cliente")
     * @ORM\JoinColumn(name="id_cliente", referencedColumnName="id_cliente")
     */
    private $cliente;
    // getters, setters, etc...
}

It is possible to do the following search ?

$criteria = Criteria::create()->where(Criteria::expr()->contains('cliente.nome', 'Felippe'));
$pedidos = $this->entityManager->getRepository('Admin\Models\Pedido')
        ->matching($criteria);

The following error is being returned:

Unrecognized field: client.name

I developed a package of utility classes to handle the searches of the jQuery Datatables plugin, and for this I created a Genericdao.

1 answer

1


From what I understand, you need a collection of orders whose name of the customer who placed the orders is "Felippe", correct?

I would do it using a DQL even:

<?php

namespace Admin\Repositories; // ou outro namespace à sua escolha

use Doctrine\ORM\EntityRepository;

class PedidoRepository extends EntityRepository

public function findByClienteNome($nome)
{
    return $this
        ->getEntityManager()
        ->createQuery('
            SELECT p
            FROM Admin\Models\Pedido p
            JOIN p.cliente c
            WHERE c.name = :name')
        ->setParameter('name', $nome)
        ->getResult();
}

Then the use would be like this:

$pedidos = $this
    ->getEntityManager()
    ->getRepository('Admin\Models\Pedido')
    ->findByClienteNome('Felippe');

By the way, you need to discriminate in your model of Pedido what is the repository of objects of type Pedido:

<?php

namespace Admin\Models;

/**
 * @ORM\Entity(repositoryClass="Admin\Models\PedidoRepository")
 */
class Pedido
{
    // etc...
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.