CakePHP:hasOne关系为字段返回null

时间:2014-06-30 07:18:17

标签: php cakephp has-one

我有2个模型,VenueContact,其中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

2 个答案:

答案 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'
        ]
    ];
}

您在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'] ;
}

答案 1 :(得分:-1)

您应该像这样更改您的代码。

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