【问题标题】:Laravel Eloquent Update Every 30 DaysLaravel Eloquent 每 30 天更新一次
【发布时间】:2015-08-31 12:48:15
【问题描述】:

使用 Laravel 的 Eloquent 模型,如果自上次 updateDate 以来已超过 30 天,我如何在访问对象时更新它的数据?

我有另一个 API,我想确保数据是半最新的,但我想将数据缓存在我的数据库中,而不是在每次页面加载时调用他们的 API。

有没有 Laravel 每次加载模型时调用的函数,在那里我可以检查 30 天是否过去,调用 API 加载新数据,然后保存?

【问题讨论】:

  • 每 30 天一个 cron 作业?

标签: php laravel eloquent


【解决方案1】:

目前尚不清楚您如何使用 API 中的数据,但您可能会发现 Laravel 的缓存功能非常方便。具体remember()方法。

use Illuminate\Support\Facades\Cache;

// Put the result returned from the closure in the cache for 30 days
// under the key 'apidata' and serve this data off of cache if it already there
$apidata = Cache::remember('apidata', 60*24*30, function() {
        // talk to your API
        // and return the data from this closure
        return $result;
});

您可以更进一步,将其包装在服务类中,让您的生活更轻松。类似于

namespace App;

use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;

class ApiData
{
    protected $client;

    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    public function all()
    {
        return Cache::remember('apidata', 60*24*30, function() {
            $response = $this->client->get('http://httpbin.org/get');
            return $response->getBody()->getContents();
        });
    }
}

那就用吧

// Get an instance off of IoC container
$api = app('App\ApiData');
$apidata = $api->all();

【讨论】:

  • 它有什么帮助吗?
【解决方案2】:

@peter60*24*30

此答案不完整,因为您必须每秒输入一次。

60*60*24*30

应该的。

【讨论】:

    猜你喜欢
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多