我有一张很大的桌子,我想每年都有一张桌子。我需要用唯一的模型表示多个表。我已经根据年份在不同的表中实现了写入,但我不知道如何使用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);
}
}
答案 0 :(得分:1)
在模型中,您可以创建一个返回查询构建器的方法,其中$ 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;
}
}
有了它,你可以在你的控制器中使用它:
class MyController extends Controller
{
public function readManagement(Request $request){
$idManagement = $request->get('managementId');
$management = Management::getInstance()->find($idManagement);
}
}