CakePHP2.5开发:Support控制器报错未找到对应supports数据表
CakePHP 2.5:Support控制器找不到supports表的问题解决
问题描述
开发遗留CakePHP2.5应用的Support控制器时,计划加载已存在的Applicant模型查询数据,但调用控制器时持续报错:

Missing Database Table Error: Database table supports for model Support was not found.
当前Support控制器代码:
<?php class SupportController extends AppController{ public $name='Support'; public $helpers = array('Html','Form'); public function index(){ $this->loadModel('Applicant'); $appConditions = array( 'fields'=>array('first_name','surname','middle_name','maiden_name','date_of_birth'), 'order'=>array('Applicant.created DESC') ); $this->paginate['Applicant'] = $appConditions; $applicationData = $this->paginate('Applicant'); $this->set(compact('applicationData')); // $this->set('applicants', $this->Applicant->find('all')); } }
注:该控制器不需要单独模型,应直接从已存在的Applicant模型加载数据。
解决方案
CakePHP 2.x的控制器默认会尝试关联同名模型:如果不存在SupportModel,框架会自动生成一个空模型,并尝试查找对应的数据表supports,这就是报错的原因。
解决方法有两种:
方法1:禁用默认模型加载
在SupportController中添加$uses = array(),告诉控制器不需要加载任何默认模型:
<?php class SupportController extends AppController{ public $name='Support'; public $helpers = array('Html','Form'); public $uses = array(); // 新增此行,禁用默认模型加载 public function index(){ $this->loadModel('Applicant'); $appConditions = array( 'fields'=>array('first_name','surname','middle_name','maiden_name','date_of_birth'), 'order'=>array('Applicant.created DESC') ); $this->paginate['Applicant'] = $appConditions; $applicationData = $this->paginate('Applicant'); $this->set(compact('applicationData')); } }
方法2:直接指定要加载的模型
如果后续控制器需要多次使用Applicant模型,可以直接在$uses中声明,无需再调用$this->loadModel():
<?php class SupportController extends AppController{ public $name='Support'; public $helpers = array('Html','Form'); public $uses = array('Applicant'); // 直接指定要加载的模型 public function index(){ $appConditions = array( 'fields'=>array('first_name','surname','middle_name','maiden_name','date_of_birth'), 'order'=>array('Applicant.created DESC') ); $this->paginate['Applicant'] = $appConditions; $applicationData = $this->paginate('Applicant'); $this->set(compact('applicationData')); } }
内容的提问来源于stack exchange,提问作者iamdeed
相关产品推荐
相关产品推荐

