CakePHP asking for model table despite useTable = false

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

I'm creating a contact form to send an email to a specified address. I'm trying to utilize CakePHP model validations and since I don't need a table for the contact model, I've set useTable to false in the contact model. Yet I'm getting an error in the controller function that does the sending. The error is

Missing Database Table Error: Database table contacts for model Contact was not found.

pointing to the line that makes the first call to $this->Contact:

$this->Contact->validates( $this->data );

I thought this was all good to go with the CakePHP framework. Why am I wrong?

回答1:

Edit: See this answer (and comment) for CakePHP 2.x (model file should be called Contact.php)


CakePHP 1.x - Verify that your model file is called contact.php (lowercase). If it is not, CakePHP won't find your model and and will instead create an "autoModel" on runtime called Contact which uses the contacts table.



回答2:

This is a top result to a search but the information is outdated I think.

In CakePHP 2.0+ you need to set $useTable = false; in the model, the model name uses propercase (so it should be Contact and not contact as suggested) and the controller must have $uses = 'Contact'; or $uses = array('Contact'); or cake generates default model properties and tries to load a table that doesn't exist. So both of these things must be set for it to work.



回答3:

If memory serves, you're not actually setting your model:

$this->Contact->set( $this->data ); $this->Contact->validates(); 

In your code, the model isn't actually populated when you try to validate it.



回答4:

If you are using a model without a table you also need to set a schema eg

class Contact extends AppModel {     var $name = 'Contact';     var $useTable = false;     var $_schema = array(         'name' => array('type' => 'string', 'length' => 255),         'email' => array('type' => 'string', 'length' => 255),         'message' => array('type' => 'text')     ); } 


回答5:

Two things made the difference for me -- changing the file name of my model to Contact.php (instead of ContactModel.php) and commenting out var $uses = 'Contact'; in my ContactController.php.

Also, many of the tutorials out there for contact forms are for earlier versions of CakePHP. Be sure to use the correct form input structure. Here is the view for mine in Cake 2.1:

<?php      echo $this->Form->create('Contact');     echo $this->Form->inputs();     echo $this->Form->end('Send');  ?> 


回答6:

If it helps anyone, I found that if I had

var $uses = 'ModelName'; 

in my controller, it will override useTable. Remove it if you don't need it.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!