我有两个模型,Venue
和Contact
,其中一个场地有一个联系人,但一个联系人可以负责多个场地。在我的表中,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']
]];
}
问题是,当我检索场地时,Contact
字段的所有内容都设置为null
。
你的代码应该是:
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。
contactid
更改为contact_id
,并在表名中添加s
,则代码变为:
class Contact extends AppModel {
public $hasMany = ['Venue'] ;
}
class Venue extends AppModel {
public $belongsTo = ['Contact'] ;
}
你应该这样修改你的代码。
class Contact extends AppModel {
public $useTable = 'contact';
public $belongsTo = [
'Venue'=>[
'className'=>'Venue',
'foreignKey'=>'contactid',
'conditions'=>['Venue.contactid = Contact.id' ]
]];
}