按月分表如何使用 Laravel 关联模型

场景: 假如数据库有表按月分表,…, y_capture_photo_new_2020_04, y_capture_photo_new_2020_05, …;我们如何该如何写model层跟如何写模型关联呢。现在讲按月份表跟其他表(不是按月分表的表),和其他按月分表的模型关联没有实践过,暂时不写,如果以后实践过会补上。
解决
以下是模型中的代码:

class YCaptureData extends Model
{
    protected $timestamp = false;
    protected static $yearMonth;

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

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

        return Parent::getTable();
    }

    public function location()
    {
        return $this->belongsTo(YLocation::class, 'location_id');
    }

    public function person()
    {
        return $this->belongsTo(YPeoplelib::class, 'person_id');
    }
}

使用

$year = date('Y');
$month = date('m');
$user = Auth::user();
$inlocations = YUserFavoriteLocation::where('user_id', $user->id)>pluck('location_id')->toArray();

$events = new YCaptureData();
$events->setYearmonth($year.'_'.$month);
$ss = $events->with([
        'location' => function ($q) {
            $q->select('id', 'name', 'inout');
        },
        'person.property',
    ])
    ->whereIn('location_id', $inlocations)
    ->where('created_at', '>=', $date.' 00:00:01')
    ->where('created_at', '<=', $date.' 23:59:59')
    ->where('y_people_lib_id', '>', '0')
    ->get(['id', 'location_id', 'y_people_lib_id']);

附上参考原文(里面有按月分表和按月份表的关联)

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 3

场景 查询的东西要跨越多个时间区间要如何弄

3年前 评论
 $unionQuery = $queries->shift();
        // 循环剩下的表添加union
        $queries->each(function ($item, $key) use ($unionQuery) {
            $unionQuery->unionAll($item);
        });
        // 设置临时表的名称,添加临时表,顺序不能反过来,否则用关联约束会找不到表
        $captures = with(new YCaptureData)->setTable('union_capture')
            // 添加临时表
            ->from(DB::raw("({$unionQuery->toSql()}) as union_capture"))
            // 合并查询条件
            ->mergeBindings($unionQuery)
            // 按时间倒序
            ->orderBy('created_at', 'desc');

这个要用到联合查询,子查询,其中$queries要用到循环月份组合查询条件添到$queries集合中,相当于可以连续跨月查询

3年前 评论

@风吹过有夏天的味道 其实也可以推荐看这篇文章,我遇到的情况是看这篇文章解决 多月份查询

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!