duanhai1455
2013-03-23 21:49
浏览 35
已采纳

在php-activerecord中按关系查找

I'm trying on php-activerecord for a project – I've used it before in Lithium and CodeIgniter – but I am stuck at something that I think should be pretty easy. But I simply can not wrap my head around it.

So, I've got two tables:

post       |id  |title  |content
           ----------------------
           |1   |Test   |Lorem...

and:

post_meta  |id  |post_id  |publish_date
           ----------------------------
           | 1  |1        |2013-03-23

Now, if I would like to match the title in the post table, and the publish_date in the post_meta-table – how would I go about in the simplest and most elegant way?

As it stands now I seem to have to do two separate queries, first at the meta table to extract the posts with the correct publish_date – and then loop through that one until I find a matching title. Or I can use relationships ($has_one and $belongs_to) – but that way it feels like I am doing it the "other way around" when I want to extract my post-data ($postMetas->post->content).

Feel free to come up with ideas and solutions – or even alternatives to an ORM that makes this is simple and elegant as possible.

图片转代码服务由CSDN问答提供 功能建议

我正在尝试使用php-activerecord进行项目 - 我之前在Lithium和CodeIgniter中使用过它 - 但是 我陷入了一些我觉得应该很容易的事情。 但我根本无法绕过它。

所以,我有两个表:

  post | id | title  | content 
 ---------------------- 
 | 1 |测试| Lorem ... 
   
 \  n 

和:

  post_meta | id | post_id | publish_date 
 ---------------------  ------- 
 |  1 | 1 | 2013-03-23 
   
 
 

现在,如果我想匹配post表中的 title , post_meta表中的 publish_date - 我将如何以最简单和最优雅的方式进行?

现在看来,我似乎必须分开两个 查询,首先在元表中使用正确的publish_date提取帖子 - 然后循环遍历那个,直到找到匹配的标题。 或者我可以使用关系( $ has_one $ belongs_to ) - 但是当我想要提取帖子时,感觉就像我正在做“其他方式” -data( $ postMetas-> post-> content )。

随意提出想法和解决方案 - 甚至是ORM的替代品 这使得它尽可能简单而优雅。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dpje52239 2013-03-24 14:20
    已采纳

    You can just use a joined structure in a finder. Check out this part of the manual.

    Basically, it says you can join using known connections, and use those as base for what you get returned. The books examples on that page are quite good, see:

    # fetch all books joining their corresponding author
     7 $book = Book::all(array('joins' => array('author')));
     8 # sql => SELECT `books`.* FROM `books`
     9 #      INNER JOIN `authors` ON(`books`.author_id = `authors`.id)
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题