Kohana 立即获取所有关系

发布于 2024-10-18 09:36:34 字数 497 浏览 5 评论 0原文

是否可以一次获取所有对象关系?

目前,我在视图中循环显示帖子评论 ($this->post->comments->find_all()),但这似乎不是最好的主意 (那么缓存怎么样?)。

你通常如何解决这个问题?

编辑 情况是这样的。当我显示最新帖子时(总共大约 15000 个,每页 25 个),我得到了一个帖子控制器。

在 Post 模型中,我设置了关系: has_many 与评论、用户、选项。在同一模型中,我得到所有带有限制和偏移量的帖子(用于分页)。

在视图中,我有一个 foreach 循环,并且正在显示帖子列表:

foreach($posts as $post)
{
    /// here in the view I have another loop for comments and options
}

现在的问题是:如何添加缓存?

Is it possible to get all object relations at once?

Currently, I'm showing post comments in a loop in the view ($this->post->comments->find_all()) however it does not seem to be the best idea (what about caching then?).

How do you usually solve that?

Edit
Here's the situation. I got a post controller when I display latest posts (circa 15000 total, 25 per page).

In Post model I've set up relations: has_many with comments, users, options. In the same model I'm getting all posts with limit and offset (for pagination).

In the view I have a foreach loop and I'm displaying posts list:

foreach($posts as $post)
{
    /// here in the view I have another loop for comments and options
}

Now the issue is: how to add cache?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

锦欢 2024-10-25 09:36:34

据我所知,这是正常用法。

如果您想使用缓存,请查看 cached() 函数。它不做任何缓存,但返回一个可以序列化然后缓存的对象。用法是:

$results = Cache::instance()->get('item');

if ( ! $results)
{
    $results = $this->post->comments->find_all()->cached();

    $six_hours = 21600;

    // Save to the cache
    Cache::instance()->set('item', $results, $six_hours);
}

foreach($results as $comment)
{
    var_dump($comment);
}

请注意,文件缓存驱动程序自动序列化数据,我假设其他驱动程序在内部做了一些魔法来存储缓存的对象。

That's normal usage as I see it.

If you want to make use of caching then take a look at the cached() function. It doesn't do any caching, but returns an object that can be serialized and then cached. The usage would be:

$results = Cache::instance()->get('item');

if ( ! $results)
{
    $results = $this->post->comments->find_all()->cached();

    $six_hours = 21600;

    // Save to the cache
    Cache::instance()->set('item', $results, $six_hours);
}

foreach($results as $comment)
{
    var_dump($comment);
}

Just a note, the file cache driver automatically serializes the data and I assume the other drivers do some magic internally to store the cached object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文