How can implement tables based on year in Laravel, like Orders2020
, Orders2019
, Orders2018
etc. And how to switch between?
Advertisement
Answer
I have a model with huge datas, and every month it will generate nearly 10 million+ records, so I split its table horizon too.
The solution is like this below,
In your Order model:
JavaScript
x
use IlluminateSupportCarbon;
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);
}
}
So you can get the table you want:
JavaScript
$orders2018 = new Order('2018');
$orders2018->where( )->get();
$orders = Order::where( )->get(); // will search from the table this year.