-1

I have 2 models, Venue and Contact, where 1 venue has 1 contact, but 1 contact can be responsible for many venues. In my tables, venue.contactid references the column contact.id

My models look like this:

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

The problem is that, when I retrieve the Venue, the Contact field has everything set to null.

Jonno_FTW
  • 8,601
  • 7
  • 58
  • 90

2 Answers2

2

Your code should be:

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

You made some mistakes between hasOne and belongsTo and other relationships, have a look here http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html.

Anyway, you should try to keep CakePHP convention to simplify your code. If you change your field contactid to contact_id and add an s to your table names, your code becomes:

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

class Venue extends AppModel {  
    public $belongsTo = ['Contact'] ;
}
Holt
  • 36,600
  • 7
  • 92
  • 139
  • Thanks for this, I'll try these when I get back to work. I'm new to CakePHP and I inherited the database from a previous developer. – Jonno_FTW Jun 30 '14 at 11:18
0

You should change your Code like this.

class Contact extends AppModel {  
     public $useTable = 'contact';
     public $belongsTo = [
      'Venue'=>[
            'className'=>'Venue',
            'foreignKey'=>'contactid',
            'conditions'=>['Venue.contactid  =  Contact.id' ]
      ]];
}
Syam Mohan M P
  • 1,047
  • 8
  • 23