Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine - FindBy on One To Many relation

lets suppose i have 'product' entity

/**
* @ORM\Entity
* @ORM\Table(name="es_product")
*/
class Product extends \Kdyby\Doctrine\Entities\BaseEntity {

/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue
 */
private $id;

... 

/**
 * @ORM\OneToMany(targetEntity="ProductLang", mappedBy="product", cascade={"ALL"}, indexBy="iso")
 */
protected $contentLang;

...

and ProductLang entity

/**
* @ORM\Entity
* @ORM\Table(name="es_product_lang")
*/
class ProductLang  extends \Kdyby\Doctrine\Entities\BaseEntity {

/**
 * @ORM\Id
 * @ORM\ManyToOne(targetEntity="\App\Modules\CmsAdmin\Model\Lang")
 */
protected $lang;

/**
 * @ORM\Id
 * @ORM\ManyToOne(targetEntity="Product", inversedBy="contentLang")
 */
protected $product;

/**
 * @ORM\Column(type="string")
 */
protected $name;

as you can see there is a one to many connection between Product and ProductLang

The question is, is there a possibility to use doctrine's 'findBy()' method from 'Product' repository to find products based on productLang.name?

I know i can do something like

productLangRepo->findBy( [ 'product' => $product, 'name' => $name]) 

but I need to stay in productRepo, that means, I would like to do something like

productRepo->findBy( [ 'contentLang["iso"]->name' => $name ]) 
like image 278
xrep Avatar asked Sep 16 '25 01:09

xrep


1 Answers

i think you are approaching this the wrong way. What you should do is use findBy on a language repo:

$language = productLangRepo->findBy(array('name' => $name));

and then get the connected products from that (since you have a 2 way connection):

$productsForLanguage = $language->getProduct() //btw since it is many to one it should be named products not product.

Then you will have a Product collection that you can filter. If you still want to go from the product repo side you will have to use DQL or Criteria to write more complex filters.

like image 152
Auris Avatar answered Sep 17 '25 15:09

Auris