我有一个Card
模型,有很多笔记。每个笔记都有一个作者。我渴望在show
CardsController
行动中加载单张卡片,如下所示:
$card = $card->load(['notes' => function($query){
$query->orderBy('created_at', 'desc')->limit(8);
}, 'notes.author']);
此查询有效。我想现在将其重构为模型范围,以便我可以在控制器中调用$card = Card::popular()
。因此,请将此方法添加到我的Card
模型中:
public function scopePopular()
{
$results = $this->with(['notes' => function($query){
$query->orderBy('created_at', 'desc')->limit(8);
}, 'notes.author']);
return $results;
}
这会弄乱一切。当没有什么能真正破解时,我开始得到难以理解的模板错误。
我做错了什么?
答案 0 :(得分:0)
为了将其用作静态函数并仍然能够访问类中的静态方法,请使用self::
而不是$this->
。
public function scopePopular()
{
$results = self::with(['notes' => function($query){
$query->orderBy('created_at', 'desc')->limit(8);
}, 'notes.author']);
return $results;
}