我有2个模型,Venue
和Contact
,其中1个地点有1个联系人,但是1个联系人可以负责许多地点。在我的表格中,venue.contactid
引用了列contact.id
我的模特看起来像这样:
class Contact extends AppModel {
public $useTable = 'contact';
public $belongsTo = [
'Contact'=>[
'className'=>'Venue',
'foreignKey'=>'contactid',
'conditions'=>['Contact.id = Venue.contactid']
]];
}
class Venue extends AppModel {
public $useTable = "venue";
public $hasOne = [
'Contact'=>[
'className'=>'Contact',
'foreignKey'=>'id',
'conditions'=>['Venue.contactid = Contact.id']
]];
}
问题在于,当我检索Venue时,Contact
字段的所有内容都设置为null
。
答案 0 :(得分:2)
您的代码应为:
class Contact extends AppModel {
public $useTable = 'contact';
public $hasMany = [ // Has many, you said it
'Venue'=> [ // Venue here, not Contact
'className'=>'Venue',
'foreignKey'=>'contactid'
] // No need of conditions, you don't have anything special
];
}
class Venue extends AppModel {
public $useTable = "venue";
public $belongsTo = [ // the contactid is in the venue table, it's a belongsTo not a hasOne
'Contact' => [
'className'=>'Contact',
'foreignKey'=>'contactid'
]
];
}
您在hasOne
和belongsTo
以及其他关系之间犯了一些错误,请查看http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html。
无论如何,您应该尝试保持CakePHP约定以简化您的代码。如果您将字段contactid
更改为contact_id
并在表名中添加s
,则代码将变为:
class Contact extends AppModel {
public $hasMany = ['Venue'] ;
}
class Venue extends AppModel {
public $belongsTo = ['Contact'] ;
}
答案 1 :(得分:-1)
您应该像这样更改您的代码。
class Contact extends AppModel {
public $useTable = 'contact';
public $belongsTo = [
'Venue'=>[
'className'=>'Venue',
'foreignKey'=>'contactid',
'conditions'=>['Venue.contactid = Contact.id' ]
]];
}