在我的Web应用程序中,我添加了缓存方法。但是问题是它没有读取传递给函数的指定的$ id。这样它的抛出错误就象:
ErrorException:未定义的变量:id
如果有人提出任何答案将很有帮助。
这里是代码->
public function relatedstory($id)
{
$key = $id;
$cacheKey = $this->getCacheKey($key);
return cache()->remember($cacheKey, Carbon::now()->addDay(1), function ()
{
$story = $this->_story->findOrFail($id);
$tags = $story->tags->random(1)->pluck('tag_id');
$storyIds = StoryTagItem::whereTagId($tags)->get()->random(4)->pluck('story_tag_id');
$relatedStory = [];
foreach($storyIds as $storyId)
{
array_push($relatedStory, $this->_story->findOrFail($storyId));
}
return StoryListResource::collection($relatedStory);
});
}
您需要function() use ($id)
才能将$id
注入关闭。
return cache()->remember($cacheKey, Carbon::now()->addDay(1), function () use ($id)
{
...
});