Search code examples
phpcakephpbelongs-to

belongsTo in Cake php


I'm following CakePHP naming convention

I need to make "many to one"-$belongsTo association Citie to Countrie ------- meaning Many Cities belong to a Country

This is the Citie Model

class Citie extends AppModel
{
    var $name = 'Citie';
    var $belongsTo = array(
        'Countrie' => array(
            'className' => 'Countrie',
            'foreignKey' => 'countrie_id'
        )
    ); 
}

You can see that there are no association data when result is returned on this link DisplayCity

This is the Countrie Model

class Countrie extends AppModel 
{
    var $name = 'Countrie';
}

Here you can see that I follow the naming convention. Display all countries


Solution

  • if you are following the convention
    so you must have City model for cities table, Country model for countries table and the foreignKey will be country_id

    <?php
    class City extends AppModel {
        var $name = 'City';
        var $belongsTo = array(
            'Country' => array(
                'className' => 'Country',
                'foreignKey' => 'country_id',
            )
        );
    }
    ?>
    

    and

    <?php
    class Country extends AppModel {
        var $name = 'Country';
        var $hasMany = array(
            'City' => array(
                'className' => 'City',
                'foreignKey' => 'country_id',
            )
        );
    
    }
    ?>