一旦添加了关系CakePHP,就无法创建模型的实例
我有三个模型:客户、公司和用户。客户和用户都属于公司,公司有以下多个客户: 客户:一旦添加了关系CakePHP,就无法创建模型的实例,cakephp,cakephp-2.3,Cakephp,Cakephp 2.3,我有三个模型:客户、公司和用户。客户和用户都属于公司,公司有以下多个客户: 客户: var $belongsTo = array( 'Company' => array( 'className' => 'Company', 'foreignKey' => 'company_id', 'dependent' => false, ), ); 公司:
var $belongsTo = array(
'Company' => array(
'className' => 'Company',
'foreignKey' => 'company_id',
'dependent' => false,
),
);
公司:
var $hasMany = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'company_id',
'dependent' => false
),
'Customer'=>array(
'className' => 'Customer',
'foreignKey' => 'company_id',
'dependent' => false
)
);
用户:
我在创建/编辑客户对象时遇到问题。下面是创建表单的方法,如下所示:
echo $this->Form->input('Customer.customer_nr');
echo $this->Form->input('Customer.name');
echo $this->Form->input('Customer.phone');
echo $this->Form->input('Customer.email');
echo $this->Form->input('Customer.address');
echo $this->Form->input('Customer.post_nr');
echo $this->Form->input('Customer.city');
echo $this->Form->input('Customer.company_id', array('value' => $current_user['company_id'], 'type'=>'hidden'));
我在表单末尾所做的是从当前登录的用户处获取公司id,并将其作为Customer.company\u id插入。在引入新关系之前,该id通常可以正常工作。但现在,当我尝试创建/编辑客户时,我收到以下SQL错误:
Error: SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'name' in where clause is ambiguous
非常感谢您的帮助
以下是控制器添加功能:
function add() {
if (!empty($this->data) ) {
$this->Customer->create();
if ($this->Customer->save($this->data)) {
$this->Session->setFlash(__('Customer was saved'), 'positive_notification');
$this->redirect(array('controller'=>'events', 'action' => 'dashboard'));
} else {
$this->Session->setFlash(__('Customer has been saved. Please, try again'), 'negative_notification');
}
}
}
该错误肯定不是由重定向引起的,因为它已经过全面测试。问题出在其他地方 它实际上与find()调用有关 尝试找到触发错误的确切代码,并将其发布到您的问题中 也许你设定了一些条件,比如
'conditions' => array(
'name' => 'john'
)
但你最好做点像
'conditions' => array(
'User.name' => 'john'
)
在您创建了用户
和公司
之间的关系之后(这只是一个示例,可能涉及的两个表是其他的),Cake开始连接这两个表。因此,当您搜索特定的名称时,mysql不知道您是想要用户
名称还是公司
名称,因为这两个表中都有名称
列
如果查看生成的查询(给出该错误的查询),您将看到两个表连接在一起。如果你不想加入,你必须指定recursive=>-1
'conditions' => array(
'name' => 'john'
),
'recursive' => -1
问题出在别的地方。它与find()
调用相关。尝试找到触发错误的确切代码,并将其发布到您的问题中。可能您设置了一些条件,如'name'=>'john'
,但您最好执行'User.name'=>'john'
之类的操作,只是用控制操作更新了问题。问题是代码中没有其他地方可以触发这个错误。哦,我刚才看到了一个条件,就像你在模型的一个函数中提到的那样。谢谢。我只是想知道为什么这以前不是个问题?你可以把它作为一个正确的答案,所以我可以选择它。
'conditions' => array(
'name' => 'john'
),
'recursive' => -1