Laravel Eloquent 关联模型查询缓存数据

Laravel Eloquent Super Relations

安装

# composer.json

"minimum-stability": "dev",
"prefer-stable": true,
$ composer require al-one/eloquent-super-relations -vvv

使用

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Alone\EloquentSuperRelations\HasSuperRelations;

class User extends Model
{

    use HasSuperRelations;

    public function profile()
    {
        return $this->hasOne('App\Profile','uid');
    }

    public function eagerLoadProfile($relation,$models = [],$where = [])
    {
        // Get cached data for relation
        if(!empty($where['uid']))
        {
            return cache()->remember("user:profile:{$where['uid']}",86400,function() use($where) {
                return Profile::find($where['uid']);
            });
        }
        // return null for get from database
        return null;
    }
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 6

没看出来怎么用?function profile() 和function eagerLoadProfile()是要一起使用?

4年前 评论

@609468798 profile()是指定关联模型,eagerLoadProfile()是在查询profile关联数据的时候调用的。

4年前 评论

@609468798 是的,eagerLoad{RelationName}()

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!