douren0558 2012-10-30 10:49
浏览 48
已采纳

如何通过Doctrine2 DQL的关联表获取远程表ID

I have the following model with 2 tables foo and bar and the foo_has_bar association in between:

enter image description here

I'm trying to get, for a given foo.id, all the corresponding bar.id's.

So far I have been able to retrieve all the entries from foo_has_bar related to a particular foo.id as follows:

$query = $em->createQuery("SELECT h FROM 'FooHasBar' h INNER JOIN h.foo f WHERE f.id = ?1");
$query->setParameter(1, $foo_id);
$results = $query->getArrayResult();

The problem is that $results only contains the id field for foo_has_bar, not the foreign keys foo_id and bar_id, and therefore I can't achieve what I want.

Is there a way, given a particular foo.id to retrieve all the corresponding bar.id's with a single DQL command?

  • 写回答

2条回答 默认 最新

  • doula4096 2012-10-30 14:57
    关注

    Assuming the entity FooHasBar has a relation foo and a relation bar respectively to Foo and Bar, the query is quite trivial:

    $q = $em->createQuery(
        'SELECT 
            b.id as bar_id, f.id as foo_id 
        FROM FooHasBar fb 
        JOIN fb.bar b 
        JOIN fb.foo f 
        WHERE f.id = :fooId'
    );
    $q->setParameter( 'fooId', $foo->getId() );
    
    $results = $query->getArrayResult();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接
  • ¥15 MATLAB中使用parfor,矩阵Removal的有效索引在parfor循环中受限制
  • ¥20 Win 10 LTSC 1809版本如何无损提升到20H1版本
  • ¥50 win10 LTSC 虚拟键盘不弹出
  • ¥30 微信小程序请求失败,网页能正常带锁访问
  • ¥15 Matlab求解微分方程,如何用fish2d进行预优?