當我試圖向數據庫中插入一張新發票時,cakephp會拋出一個錯誤,說它無法在where子句中找到列relationship.partytwo。我試圖實現的是確保發送發票的用戶在發送發票之前在relationship_users數據庫中與收到發票的人之間存在活動關係,可悲的是我所得到的只是數據庫錯誤。爲什麼cakephp引發數據庫錯誤?
這裏是我的表結構
invoices - id, to, biller, subject, description, datecreated, duedate
relationships_users - id, partyone, partytwo, expirydate,active
這裏是關係模型
<?php
class Relationship extends AppModel
{
var $name = 'Relationship';
public $useTable = 'relationships_users';
public $primaryKey = 'id';
public $belongsTo = array(
'Invoice' =>
array(
'className' => 'Invoice',
'joinTable' => 'invoice',
'foreignKey' => 'invoice_id'));
public $belongsTo = array(
'User' =>array(
'className' => 'User',
'foreignKey' =>'partyone','partytwo',
'associationForeignKey' => 'username',
));
var $validate = array(
'date' => array(
'rule' => array(
'datevalidation',
'systemDate'
),
'message' => 'Current Date and System Date is mismatched'
),
'partytwo' => array(
'userExists' => array(
'rule' => array(
'userExists',
),
'message' => 'That username doesnt exist.'
),
),
);
function datevalidation($field = array(), $compare_field = null)
{
if ($field['date'] > $compare_field)
return TRUE;
else
return FALSE;
}
function userExists($check)
{
$userExists = $this->User->find('count', array('conditions' => array('User.username'=>$check)));
if ($userExists == 1) {
return TRUE;
}
else
return FALSE;
}
}
這裏是我的發票模型
<?php
App::uses('AuthComponent', 'Controller/Component');
class Invoice extends AppModel{
var $name='Invoice';
public $useTable = 'invoices';
public $primaryKey = 'id';
public $hasMany = array(
'Relationship' =>array(
'className' => 'Relationship',
'foreignKey' =>'relationship_id',
));
var $validate = array(
'to' => array(
'relationshipExists' => array(
'rule' => array(
'relationshipExists',
),
'message' => 'sorry you dont have a relationship with that user.'
),
),
);
public function relationshipExists($check){
if($this->hasAny(array('Relationship.partytwo'=>current($check))))
{
return TRUE;
}
else
{
return FALSE;
}
}
}
這裏是我的addinvoice功能
public function addinvoice(){
$this->set('title_for_layout', 'Create Invoice');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.jpg');
$this->layout='home_layout';
if($this->request->is('post')){
pr($this->Invoice->set($this->request->data));
if($this->Invoice->validates(array('fieldList'=>array('to','Invoice.relationshipExists')))){
// $this->Relationship->create();
$this->Invoice->save($this->request->data);
$this->Session->setFlash('The invoice has been saved');
}}else {
$this->Session->setFlash('The invoice could not be saved. Please, try again.');
}
}
「Invoices」表中沒有'partytwo'字段,這就是爲什麼你會收到錯誤。你也說「一個關係有許多關係」,這隻會導致問題。我會重新思考你的模型關係,你肯定比你需要的複雜得多。 – Dunhamzzz
固定了,但它仍然拋出相同的數據庫錯誤 – user1393064