在 Laravel 中将每年分开 table

Separate table for each year in Laravel

如何在 Laravel 中实现基于年份的表格,如 Orders2020Orders2019Orders2018 等。如何切换?

我觉得你可以scope

示例:

public function scopeYear($query,$year)
{
    $this->table = 'orders'.year;
    return $query;
}
  • 要从 2019 年的 table 个订单中获取,只需使用 Order::year('2019')->get();
  • 要为 2019 年的 table 个订单创建数据,只需使用 Order::year('2019')->create($data);

我有一个大数据模型,每个月都会产生近千万+的记录,所以我也拆分了它的table horizo​​n。

解决方法如下,

在您的订单模型中:

use Illuminate\Support\Carbon;

class Order extends Model
{
    protected $table = '';
    public function __construct($year='')
    {
        parent::__construct();

        if (empty($year)) {
            $tablename = 'orders'.Carbon::now()->year;
        } else {
            $tablename = 'orders'.$year;
        }
        $this->setTable($tablename);
    }
}

所以你可以得到你想要的table:

$orders2018 = new Order('2018');
$orders2018->where(...)->get();

$orders = Order::where(...)->get(); // will search from the table this year.
Order::from('orders_2019')->get();

我有 3 个 table 具有相同的架构 我用这个结构来处理那个

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class ReportValues extends Model
{
    use HasFactory;      

    protected $fillable = [
        'id',
        'user_id',
        'report_id',
        'item_id',
        'value',
    ];

    public function scopeGenerate($query, $type, $date){
        $table_name = $type."_".$date;
        if (!Schema::hasTable($table_name)){
            Schema::create($table_name, function (Blueprint $table) {
                $table->id();
                $table->integer('user_id');
                $table->integer('report_id');
                $table->integer('item_id');
                $table->tinyText('value');     
                
                $table->unique(['report_id', 'item_id', 'user_id']);
                $table->foreign('user_id')->references('id')->on('users');
                $table->foreign('item_id')->references('id')->on('report_items');                
            });
        }        
        return $query;
    }
    
    public function scopeSalaries($query, $date){
        $this->table = 'salaries_'.$date;
        return $this;
    }

    public function scopeContracts($query, $date){
        $this->table = 'contracts_'.$date;
        return $this;
    }
}

然后使用此命令来使用它们:

每个月客户工资生成table:

ReportValues::generate('salaries', '202101')

然后

ReportValues::salaries('202101')->get()

或每年生成合同table
ReportValues::generate('contracts', '202101')
然后
ReportValues::contracts('2021')->get()

我的 table 是:

salaries_202101
contracts_2021