按月分表如何使用 Laravel 關聯模型

小彭友發表於2020-05-25

場景: 假如資料庫有表按月分表,…, 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 協議》,轉載必須註明作者和本文連結

相關文章