根據年月份分表

ignorance發表於2020-12-07

舉例

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class Log extends Model
{
    protected $guarded = [];
    protected static $yearMonth;

    public static function getLogModel($yearMonth = null)
    {
        $model = new Log();
        $model->setYearMonth($yearMonth);
        $model->getTable();

        if (!Schema::hasTable($model->getTable())) {
            DB::update('create table ' . $model->getTable() . ' like logs' );
        }

        return $model;
    }

    public function setYearMonth($yearMonth)
    {
        static::$yearMonth = $yearMonth;
    }

    public function getTable()
    {
        if (static::$yearMonth) {
            return 'logs_' . static::$yearMonth;
        }
        return Parent::getTable();
    }


}

使用

Log::getLogModel()->where('id', 1)->first()
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章