gpt4 book ai didi

mysql - 如何用唯一模型表示多个表?

转载 作者:行者123 更新时间:2023-11-28 23:12:14 24 4
gpt4 key购买 nike

我有一张很大的 table ,我想每年都有一张 table 。我需要用唯一的模型表示多个表。我已经实现了根据年份写入不同的表,但我不知道如何使用 orm 读取多个表。有什么建议吗?我正在使用 Laravel 5.3

class Management extends Model
{
protected $table = 'management_2017';

public function setTableYear($date = null){
if ( is_null($date) )
$date = \Carbon::now();
if ($date->year >= 2017)
$this->setTable('management_' . $date->year);
}
}

class MyController extends Controller
{
public function saveManagement(){
$management = new Management();
$management->setTableYear();
//... set attributes
$management->save();
}

public function readManagement(Request $request){
$idManagement = $request->get('managementId');
// I dont know how to set a table here. Default table is 'management_2017'
$management = Management::find($idManagement);
}
}

最佳答案

在您的模型中,您可以创建一个方法,该方法返回一个查询构建器并更新了 $table 属性:

class Management extends Model
{
protected $table = 'management_2017';

public function setTableYear($date = null){
if ( is_null($date) )
$date = \Carbon::now();
if ($date->year >= 2017)
$this->setTable('management_' . $date->year);
}

public static function getInstance()
{
$a = new static;
$a->setTableYear();
return $a;
}
}

这样,您就可以在您的 Controller 中使用它了:

class MyController extends Controller
{
public function readManagement(Request $request){
$idManagement = $request->get('managementId');
$management = Management::getInstance()->find($idManagement);
}
}

关于mysql - 如何用唯一模型表示多个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45464020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com