Laravel Eloquent 關聯模型查詢快取資料

Alone發表於2020-11-15

安裝

# 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 協議》,轉載必須註明作者和本文連結

相關文章