ttgive / qeephp

Automatically exported from code.google.com/p/qeephp
0 stars 0 forks source link

优化关联查询的可能途径 #62

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
可以将查询数据缓存在一个 database query cache 容器中。
每一个缓存数据按照其 id 进行索引。

这样当需要查询特定 id 的缓存数据时,可以从 database query 
cache 中获取,从
而避免数据库查询。

--------------------------

{{{
$posts = Post::find(...)->limit(10)->query();

foreach ($posts as $post) {
    foreach ($post->comments as $comment) {
        echo $comment->post->title;
    }
}
}}}

上述代码,第一次查询时查出 10 个 post 
对象的数据,然后在遍历时查询出 10 个
post 对象的所有 comment 对象时。那么在遍历 comment 
时,是否需要查询 post 对
象呢?

因为先前已经查询出了 10 个 post 
对象,如果此时再去查询,显然就是多余的操
作。因此可以从 database query cache 中直接取出先前缓存的 10 
个 post 对象数
据,并构造为 post 
对象集合返回。这种思路最大的问题时,每份数据占用了双��
�的
内存空间。

--------------------------

{{{
$posts = Post::find(...)->limit(10)->query();

foreach ($posts as $post) {
    echo count($post->comments);
}
}}}

如果要避免此处的 1+n 
查询,比较合理的解决途径仍然是将对象注册到 meta。从而
可以在第一次访问 $post->comments 时批量查询出 comment 
对象,并指定给 $post
对象。

Original issue reported on code.google.com by dualf...@gmail.com on 5 May 2008 at 8:01

GoogleCodeExporter commented 9 years ago
以空间换时间 绝对可以接受

Original comment by skyblue1...@gmail.com on 17 Jan 2009 at 4:54