Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine2 fetching rows that have manyToMany association by QueryBuilder

everyone. I have 2 entities City and POI. Mapping looks like this:

class City {
/**
 * @ORM\ManyToMany(targetEntity="POI", mappedBy="cities")
 * @ORM\OrderBy({"position" = "ASC"})
 */
protected $pois;

and

class POI {
/**
 * @ORM\ManyToMany(targetEntity="City", inversedBy="pois")
 * @ORM\JoinTable(name="poi_cities")
 */
protected $cities;

I would like to fetch all POIs that have at least 1 association with some City using QueryBuilder. I should probably use exists() function but I don't quiet know how.

like image 685
Wojciech Jasiński Avatar asked Dec 28 '25 03:12

Wojciech Jasiński


1 Answers

You'd have to Left join them and check if cities is null.

$qb->select('p', 'c')
   ->from('AcmeDemoBundle:POI', 'p')
   ->leftJoin('p.cities', 'c')
   ->where('c IS NOT NULL');

I haven't tested it, but I hope it gives you the general direction. You can read more about the QueryBuilder from here.

like image 121
kgilden Avatar answered Dec 30 '25 17:12

kgilden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!