如何在 symfony (Propel) 中连接表并使用一个查询从两个表中检索对象
我试图找到一种简单的方法来使用 Propel (在 Symfony 内部)但在一个查询中从两个连接的 Mysql 表中获取数据。
假设我做了这个简单的事情:
$comment = CommentPeer::RetrieveByPk(1);
print $comment->getArticle()->getTitle();
//Assuming the Article table is joined to the Comment table
Symfony 将调用 2 个查询来完成该操作。第一个获取评论行,下一个获取链接到评论行的文章行。
现在,我正在尝试找到一种方法来在一个查询中完成所有这些操作。我尝试使用加入它们,
$c = new Criteria();
$c->addJoin(CommentPeer::ARTICLE_ID, ArticlePeer::ID);
$c->add(CommentPeer::ID, 1);
$comment = CommentPeer::doSelectOne($c);
但是当我尝试使用它获取 Article 对象时,
$comment->getArticle()
它仍然会发出查询来获取 Article 行。我可以轻松地清除所有选定的列并选择我需要的列,但这不会给我想要的 Propel 对象,而只是查询原始结果的数组。
那么,如何才能通过一个查询获得两个(或更多)连接表的填充推进对象呢?
谢谢,
JP
I'm trying to get an easy way to fetch data from two joined Mysql table using Propel (inside Symfony) but in one query.
Let's say I do this simple thing:
$comment = CommentPeer::RetrieveByPk(1);
print $comment->getArticle()->getTitle();
//Assuming the Article table is joined to the Comment table
Symfony will call 2 queries to get that done. The first one to get the Comment row and the next one to get the Article row linked to the comment one.
Now, I am trying to find a way to make all that within one query. I've tried to join them using
$c = new Criteria();
$c->addJoin(CommentPeer::ARTICLE_ID, ArticlePeer::ID);
$c->add(CommentPeer::ID, 1);
$comment = CommentPeer::doSelectOne($c);
But when I try to get the Article object using
$comment->getArticle()
It will still issue the query to get the Article row. I could easily clear all the selected columns and select the columns I need but that would not give me the Propel object I'd like, just an array of the query's raw result.
So how can I get a populated propel object of two (or more) joined table with only one query?
Thanks,
JP
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该有一个
CommentPeer::doSelectJoinArticle()
方法,可以用来执行此操作。如果你不这样做,那么你可能没有在数据库模式中使用 MySQL 的 InnoDB 存储引擎或外键引用,这是我强烈推荐的 - 它不仅允许 Propel 将这些额外的 JOIN 方法添加到其生成的模型代码中,但是您将从符合 ACID 的数据库中获得许多好处。另一种方法是自己编写
CommentPeer::doSelectJoinArticle()
方法 - 此链接将描述该过程,但该过程的长度可能会让您选择第一个选项:)You should have a
CommentPeer::doSelectJoinArticle()
method, which can use to do this. If you don't, then you're probably not using MySQL's InnoDB storage engine or foreign key references in your database schema, which is something I highly recommend - not only will it allow Propel to add these extra JOIN methods to its generated model code, but you will gain many benefits from an ACID-compliant database.The alternative is to write the
CommentPeer::doSelectJoinArticle()
method yourself - this link will describe the process, but the length of the process may make you choose the first option :)