Doctrine2 通过 QueryBuilder 获取具有多对多关联的行

发布于 2024-12-06 06:49:11 字数 450 浏览 0 评论 0 原文

每个人。 我有 2 个实体 City 和 POI。映射看起来像这样:

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

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

想使用 QueryBuilder 获取与某个城市至少有 1 个关联的所有 POI。我可能应该使用exists()函数,但我不知道如何使用。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

×眷恋的温暖 2024-12-13 06:49:11

您必须Left join它们并检查cities是否为空。

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

我还没有测试过,但我希望它能为您提供总体方向。您可以从 QueryBuilder 的更多信息“noreferrer”>此处

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.

只涨不跌 2024-12-13 06:49:11

Docrine2 于 2013 年进行了更改,因此另一个解决方案显示错误错误:无法在非结果变量上添加条件。 现在我们不能仅将连接别名用作条件变量。我们应该使用它的任何属性,例如 c.id

因此,您应该将代码修复为

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

如果您想选择没有任何城市的实体,请使用 IS空

$qb->leftJoin('p.cities', 'city')
    ->where('city.id IS NULL')
    ->getQuery()
    ->execute();

问题描述以及负责该问题的提交链接 - http://www .doctrine-project.org/jira/browse/DDC-2780

Docrine2 was changed in 2013, so the other solution displays error Error: Cannot add having condition on a non result variable. Now we cannot use joined alias just as a condition variable. We should use any of its properties like c.id

So you should fix the code to

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

If you want to select entities that does not have any cities, use IS NULL.

$qb->leftJoin('p.cities', 'city')
    ->where('city.id IS NULL')
    ->getQuery()
    ->execute();

Description of a problem and link to the commit that responsible for that - http://www.doctrine-project.org/jira/browse/DDC-2780

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文