Laravel 框架 操作表结构相同不同表名的数据表

比如表:user_card_logs_2021、user_card_logs_2022、user_card_logs_2023,表结构相同,但是分别存储2021、2022、2023年的数据.

1、UserCardLog 模块里
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UserCardLog extends BaseModel
{
    /**
     * 构造函数里面设置 表名 时间(年份 如:2023)
     * @param string | array $year
     */
    public function __construct( $year = null )
    {
        parent::__construct();
        if($year){
            if(is_array($year)){
                // 此处是因为 Model::mark([0=>$year]) 模式
                $tableName = 'user_card_logs_'.$year[0];
            }else{
                $tableName = 'user_card_logs_'.$year;
            }
            $this->setTable($tableName);
        }
    }
    /**
     * 用于关联查询的时候设置表名,方式是使用本地作用域scope
     */
    public function scopeSetMysqlTable($query, $year=null)
    {
        if($year){
            $year = $year ? $year : date('Y',time());
            $table = 'user_card_logs_'.$year;
            $query->from($table);
        }
        return $query;
    }
}
2、使用其他表,关联查询UserCardLog 模块。比如:一对一查询,对hasOne进行修改
<?php

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Rennokki\QueryCache\Traits\QueryCacheable;
class SchoolCardRecord extends BaseModel
{
    public function userCardLog(){
        $instance = new UserCardLog();
        $table = $instance->getTable;
        return $this->newHasOne($instance->newQuery(), $this, $table.'forgin_id', 'id')->where($table.'target_type',3);
    }
}
3、使用方法
#一对一关联查询,查询user_card_logs_2022表里的数据
SchoolCardRecord::with(['userCardLog'=>function($q){
                                    $q->SetMysqlTable(2022)->select(['id'])->where('id','>',10);
                                }])->limit(1)->get()->toArray();
#UserCardLog模型查询
#方式1
UserCardLog::SetMysqlTable(2023)->limit(1)->get()->toArray();
#方式2
UserCardLog::make([0=>2021])->with(['user'])->limit(1)->get()->toArray();
#方式3
$model = new UserCardLog(2022);

(注:此方法并不完善,不喜勿喷,若有误请指教)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容