CakePHP:hasOne关系为字段返回null

CakePHP:hasOne关系为字段返回null,php,cakephp,has-one,Php,Cakephp,Has One,我有两种型号,场馆和联系人,其中一个场馆有一个联系人,但一个联系人可以负责多个场馆。在我的表格中,vention.contactid引用列contact.id 我的模型是这样的: class Contact extends AppModel { public $useTable = 'contact'; public $belongsTo = [ 'Contact'=>[ 'className'=>'Venue',

我有两种型号,
场馆
联系人
,其中一个场馆有一个联系人,但一个联系人可以负责多个场馆。在我的表格中,
vention.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']
        ]];
}

问题是,当我检索场地时,
联系人
字段的所有内容都设置为
null

您应该这样更改代码

class Contact extends AppModel {  
     public $useTable = 'contact';
     public $belongsTo = [
      'Venue'=>[
            'className'=>'Venue',
            'foreignKey'=>'contactid',
            'conditions'=>['Venue.contactid  =  Contact.id' ]
      ]];
}
您的代码应该是:

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
以及其他关系之间犯了一些错误,请查看此处

无论如何,您应该尽量保持CakePHP约定以简化代码。如果您将字段
contactid
更改为
contact\u id
,并在表名中添加
s
,则您的代码将变为:

class Contact extends AppModel {  
    public $hasMany = ['Venue'] ;
}

class Venue extends AppModel {  
    public $belongsTo = ['Contact'] ;
}

我做了更改,但没有解决问题。你是否与$hasMany联系过?谢谢你,我回去工作后会试试这些。我是CakePHP新手,从以前的开发人员那里继承了数据库。