按月分表如何使用 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 协议》,转载必须注明作者和本文链接
推荐文章: