多对多关系的 DQL 语句
我对 DQL 的工作原理感到困惑,并且确实需要一些帮助。
我有三个表,分别称为“Band”、“Agent”和“BandAgent”。
BandAgent是多对多关系的中间表,包含agent_id和band_id。
如何使用 DQL 语句检索与特定 band_id 相关的所有代理?
编辑
此代码有效,但我不知道这是否是正确的方法。屏幕上回显所有与 BandID 相关的关联特工:
//$band is a Band Table Row
$bandAgentTable = Doctrine_Core::getTable('BandAgent');
$agentTable = Doctrine_Core::getTable('Agent');
$bandAgentTable = $bandAgentTable->findByBandId($band->getId());
foreach ($bandAgentTable as $bandAgent) {
$agent = $agentTable->findById($bandAgent['agent_id']);
echo $agent[0]['name'];
}
编辑 2
我最终阅读了大量有关 Doctrine 的内容,并最终放弃了 Magic Finders。如果有人感兴趣,以下代码是我最终为多对多问题所做的事情:
public function getRelatedAgents() {
$q = Doctrine_Query::create()
->from('Band b')
->leftJoin('b.Agents a')
->where('b.id = ?', $this->getId());
$bands = $q->fetchArray();
return $bands[0]['Agents'];
}
I'm confused about how DQL works, and really need some help here.
I have three tables, called "Band", "Agent", and "BandAgent".
BandAgent is the middle table for a Many-to-many relationship, containing agent_id and band_id.
How can I retrieve all Agents related to a specific band_id using a DQL statement?
EDIT
This code works, but I don't know if it is the right way to do it. Echos to the screen all associated Agents related to a Band by BandID:
//$band is a Band Table Row
$bandAgentTable = Doctrine_Core::getTable('BandAgent');
$agentTable = Doctrine_Core::getTable('Agent');
$bandAgentTable = $bandAgentTable->findByBandId($band->getId());
foreach ($bandAgentTable as $bandAgent) {
$agent = $agentTable->findById($bandAgent['agent_id']);
echo $agent[0]['name'];
}
EDIT 2
I ended up reading a heck of a lot about Doctrine, and ended up moving away from Magic Finders. The following code is what I ended up doing for my Many-to-Many issue, if anyone is interested:
public function getRelatedAgents() {
$q = Doctrine_Query::create()
->from('Band b')
->leftJoin('b.Agents a')
->where('b.id = ?', $this->getId());
$bands = $q->fetchArray();
return $bands[0]['Agents'];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Doctrine 提供魔法查找器。
这将搜索表
BandAgent
中的Band
列,并将其与变量$band
进行匹配。更新:为了响应您的编辑,您还可以同时搜索两列。
Doctrine offers Magic Finders.
This will search the column
Band
in the tableBandAgent
and match it with the variable$band
.Update: In response to your edit, you can also search on two columns together.