缓存 eloquent 模型及其所有关系,然后将其转换回具有关系的模型?
Cache eloquent model with all of it's relations then convert it back to model with relations?
我正在尝试使用缓存优化一个运行速度很慢的项目。我面临一个问题,我不太明白如何缓存完整的 eloquent 模型及其关系,然后将它们隐藏回所有关系完好无损的模型。这是我的代码片段
if (Cache::has($website->id.'_main_page')) {
$properties = (array) json_decode(Cache::get($website->id.'_main_page'));
$page = Page::hydrate($properties);
}else{
$expiresAt = now()->addMinutes(60);
$page = Page::with(['sections', 'pageSections.sectionObjects'])->where('website_id', $website->id)->where('main', 1)->first();
Cache::put($website->id.'_main_page', $page->toJson(), $expiresAt);
}
问题是,hydrate
似乎将此数据转换为一个集合,而实际上它应该是一个模型。因此,后来我无法访问它的任何属性而不会出现它们不存在的错误。 $properties
变量看起来很完美,我会使用它,但我需要 laravel 将其理解为页面模型而不是 stdClass,我还需要将所有关系转换为它们适当的模型。这可能吗?非常感谢任何帮助
有什么理由不能像这样使用缓存
$page = Cache::remember($website->id.'_main_page', 60 * 60, function () use ($website) {
return Page::with(['sections', 'pageSections.sectionObjects'])
->where('website_id', $website->id)
->where('main', 1)
->first();
});
有条件的
$query = Page::query();
$key = $website->id.'_main_page';
if (true) {
$query = $query->where('condition', true);
$key = $key . '_condition_true';
}
$query::with(['sections', 'pageSections.sectionObjects'])
->where('main', 1)
$page = Cache::remember($key, 60 * 60, function () use ($query) {
return $query->first();
});
我正在尝试使用缓存优化一个运行速度很慢的项目。我面临一个问题,我不太明白如何缓存完整的 eloquent 模型及其关系,然后将它们隐藏回所有关系完好无损的模型。这是我的代码片段
if (Cache::has($website->id.'_main_page')) {
$properties = (array) json_decode(Cache::get($website->id.'_main_page'));
$page = Page::hydrate($properties);
}else{
$expiresAt = now()->addMinutes(60);
$page = Page::with(['sections', 'pageSections.sectionObjects'])->where('website_id', $website->id)->where('main', 1)->first();
Cache::put($website->id.'_main_page', $page->toJson(), $expiresAt);
}
问题是,hydrate
似乎将此数据转换为一个集合,而实际上它应该是一个模型。因此,后来我无法访问它的任何属性而不会出现它们不存在的错误。 $properties
变量看起来很完美,我会使用它,但我需要 laravel 将其理解为页面模型而不是 stdClass,我还需要将所有关系转换为它们适当的模型。这可能吗?非常感谢任何帮助
有什么理由不能像这样使用缓存
$page = Cache::remember($website->id.'_main_page', 60 * 60, function () use ($website) {
return Page::with(['sections', 'pageSections.sectionObjects'])
->where('website_id', $website->id)
->where('main', 1)
->first();
});
有条件的
$query = Page::query();
$key = $website->id.'_main_page';
if (true) {
$query = $query->where('condition', true);
$key = $key . '_condition_true';
}
$query::with(['sections', 'pageSections.sectionObjects'])
->where('main', 1)
$page = Cache::remember($key, 60 * 60, function () use ($query) {
return $query->first();
});