我正在尝试优化一个使用缓存工作速度很慢的项目。我面临一个问题,我不太明白如何缓存完整的 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 将其理解为 Page 模型而不是 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();
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句