CakePHP: hasOne关系对字段返回null


CakePHP: hasOne relationship returns null for fields

我有两个模型,VenueContact,其中一个场地有一个联系人,但一个联系人可以负责多个场地。在我的表中,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'
        ]
    ];
}

你在hasOnebelongsTo和其他关系之间犯了一些错误,看看这里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'] ;
}

你应该这样修改你的代码。

class Contact extends AppModel {  
     public $useTable = 'contact';
     public $belongsTo = [
      'Venue'=>[
            'className'=>'Venue',
            'foreignKey'=>'contactid',
            'conditions'=>['Venue.contactid  =  Contact.id' ]
      ]];
}