2015-09-09 36 views
0

我不确定这是最近发生了变化,还是我以前从未注意过,但来自Eloquent Accessor的响应并未保留,这意味着每次调用访问器方法单次。在这个特定的例子中,这导致查询多次不必要的。这里有一个例子:Laravel Eloquent:保存访问者响应

<?php 
//Career Model 
class Career extends Model { 
    public function seasons() 
    { 
     return $this->hasMany('Season', 'career_id'); 
    } 

    pubic function getSeasonsCountAttribute() 
    { 
     return $this->seasons()->count(); 
    } 
} 

//Season Model 
class Season extends Model { 
} 

//Blade Template 
@if($career->seasonsCount) 
    <div>Seasons Count: {{ $career->seasonsCount }}</div> 
@endif 

从代码查询将被运行两次这一点,因为$ seasonsCount被访问两次。

select count(*)as seasons where aggregate seasonscareer_id ='12316'和seasonscareer_id不为空

seasons其中seasons中选择总数(*)。 career_id ='12316'和seasonscareer_id不为空

我知道我可以做这两个东西一个避免这种情况:

pubic function getSeasonsCountAttribute() 
{ 
    if(is_null($this->seasonsCountCache)) 
    { 
     $this->seasonsCountCache = $this->seasons()->count(); 
    } 

    return $this->seasonsCountCache; 
} 

OR

@if($seasonsCount = $career->seasonsCount) 
    <div>Seasons Count: {{ $seasonsCount }}</div> 
@endif 

虽然这些会的工作,我想找到,如果在Laravel中有一些方法可以防止每次访问它。这似乎是一个非常奇怪的设计决定,需要每次调用该函数。

回答

0

对于我来说,查询生成器的工作方式看起来并不奇怪。

这就像你在说:“这很奇怪,因为当我做

$careers = Career::all(); 
$newCareers = Career::all(); 

它激发两个查询”

当然它的好,这是你的责任来缓存数据,你已经事先检索。

你的解决方案与seasonsCountCache属性,虽然看起来不错。