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条)

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧