Laravel 4 - Eloquent:在访问之前是否可以查询所有关系?

时间:2022-01-14 07:56:01

I'm trying to cache a DB query(and its relations), but after experimenting with Eloquent ORM I realized that the relations are only queried when they're being accessed - which is, in my case, within the views.
The problem is that the controller contains the whole caching process, and since the relations are accessed with the views; these relations are never cached.

我正在尝试缓存数据库查询(及其关系),但在尝试使用Eloquent ORM之后,我意识到只有在访问它们时才会查询这些关系 - 就我而言,在视图中。问题是控制器包含整个缓存过程,并且因为关系是通过视图访问的;这些关系永远不会被缓存。

So I've been looking for a way to pre-query every relation within the controller, the obvious solution was to access each relation manually within the controller, but it doesn't seem like an optimal solution.

所以我一直在寻找一种方法来预先查询控制器中的每个关系,显而易见的解决方案是在控制器内手动访问每个关系,但它似乎不是最佳解决方案。

TL;DR: Is there a way to query all(or a subset of) Eloquent relations before actually accessing them?

TL; DR:有没有办法在实际访问之前查询所有(或子集)Eloquent关系?

1 个解决方案

#1


0  

Look into eager loading.

看看急切的装载。

class Bar extends Eloquent
{
    public function foos()
    {
        return $this->hasMany('Foo');
    }
}

$bars = Bar::with('foos')->get();

$bars now contains all Bars with all Foos preloaded in 2 SQL queries.

$ bars现在包含所有在2个SQL查询中预加载所有Foos的Bars。

#1


0  

Look into eager loading.

看看急切的装载。

class Bar extends Eloquent
{
    public function foos()
    {
        return $this->hasMany('Foo');
    }
}

$bars = Bar::with('foos')->get();

$bars now contains all Bars with all Foos preloaded in 2 SQL queries.

$ bars现在包含所有在2个SQL查询中预加载所有Foos的Bars。