【问题标题】:How to dynamically change $table name in Laravel Model?如何在 Laravel 模型中动态更改 $table 名称?
【发布时间】:2019-07-08 20:12:54
【问题描述】:

我正在尝试从根据日期不断更改其后缀的表中提取数据。例如 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 还很陌生。非常感谢您的帮助。

【问题讨论】:

  • 不能直接赋值给属性,但是可以在构造函数中设置
  • 我讨厌成为“那个人”,但为什么要将报告存储在特定日期的表格下?它没有理由被称为关系数据库;)

标签: php laravel-5


【解决方案1】:

您不需要 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

【讨论】:

  • 我必须使用 Eloquent 模型参考,因为它连接到另一个数据库服务器。与主连接不同。所以 DB::select 在这种情况下不起作用。所以我不得不直接调用模型
  • @Vester 你也可以使用DB 外观的多个数据库连接。 $users = DB::connection('foo')->select(...); 参考:laravel.com/docs/5.8/…
  • 感谢大家的建议。我设法通过在默认构造函数中声明值来使其工作。
猜你喜欢
  • 2018-12-27
  • 1970-01-01
  • 2015-12-26
  • 1970-01-01
  • 2020-10-19
  • 1970-01-01
  • 2015-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多