如何在 Laravel 中实现基于年份的表格,例如 Orders2020
、Orders2019
、Orders2018
等,以及如何切换?
最佳答案
我有一个数据量很大的模型,每个月都会生成近千万条以上的记录,所以我也对其表范围进行了分割。
解决方案如下,
在您的订单模型中:
use Illuminate\Support\Carbon;
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);
}
}
这样你就可以获得你想要的表格:
$orders2018 = new Order('2018');
$orders2018->where(...)->get();
$orders = Order::where(...)->get(); // will search from the table this year.
关于php - Laravel 中每年都有单独的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59482092/