Search code examples
phpsymfonydoctrine-ormsymfony-2.8

Query using a summary table symfony2


There are my entities:

Order entity with property product

/**
 * @var string
 *
 * One Order has Many OrderProduct.
 * @ORM\OneToMany(targetEntity="OrderProduct", mappedBy="order")
 */
private $product;

/**
 * CatalogOrder constructor.
 */
public function __construct() {
    $this->product = new ArrayCollection();
}

OrderProduct entity with properties product, order and number (this entity is needed to store the quantity of ordered products)

/**
 * @ORM\ManyToOne(targetEntity="CatalogOrder", inversedBy="product")
 * @ORM\JoinColumn(name="order_id", referencedColumnName="id")
 * @Assert\NotBlank()
 */
private $order;

/**
 * @ORM\ManyToOne(targetEntity="Product", inversedBy="order")
 * @ORM\JoinColumn(name="product_id", referencedColumnName="id")
 * @Assert\NotBlank()
 */
private $product;

/**
 * @var int
 *
 * @ORM\Column(name="number", type="integer")
 */
private $number;

Product entity with property order

/**
 * @ORM\OneToMany(targetEntity="OrderProduct", mappedBy="product")
 */
private $order;

public function __construct()
{
    $this->order = new ArrayCollection();
}

I want to look for the name of the goods in the orders on the frontend, i.e. Enter "be" and displays all orders with the product "beer".

My guess is not true:

$qb->join('o.product', 'p')
    ->where('p.product.name LIKE :name')
    ->setParameter('name', '%'.$filters['productName'].'%');

Solution

  • I see where your issue is now. That is not how you deal with joined entities. You need to also join the Product entity from OrderProduct. It should look like this:

    $qb
        ->join('o.product', 'op')
        ->join('op.product', 'p')
        ->where('p.name LIKE :name')
        ->setParameter('name', '%'.$filters['productName'].'%')
    ;
    

    You should really rename $product in your Order entity to be $orderProduct so it matches the actual entities, and becomes less confusing. Once you do that your query will make more sense:

    $qb
        ->join('o.orderProduct', 'op')
        ->join('op.product', 'p')
        ->where('p.name LIKE :name')
        ->setParameter('name', '%'.$filters['productName'].'%')
    ;