如何在Laravel Model中动态更改$ table名称?

时间:2019-07-08 10:09:27

标签: php laravel-5

我正在尝试从一个表中提取数据,该表会根据日期不断更改其后缀。例如6月的Report201906、7月的Report201907。

所以我想连接到带有当前日期后缀的表。例如,当前月份为7月。所以我想连接到Report201907

我尝试过:

protected $connection = 'mysql2';
protected $primaryKey = 'id';
protected $current_month = date('Ym',strtotime(date('Y-m')." -1 month"));
protected $table = 'Report'.$current_month; //Hoping to connect to Report201907

但是我得到了错误 常量表达式包含无效的操作。我对laravel和PHP还是陌生的,我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

您不需要laravel Eloquent或Model即可满足要求,对于RAW SQL查询,只需在控制器中使用use laravel DB门面即可。

在控制器中使用外观,例如:

use Illuminate\Support\Facades\DB;

public function index() {

   $current_month = date('Ym',strtotime(date('Y-m')." -1 month"));

   $table = 'Report'.$current_month;    // btw this returns 'Report201906' not 'Report201907'

   $records = DB::select('select * from '.$table);

   return $records;

}

有关详细信息,请提供官方文档: https://laravel.com/docs/5.8/database