Search code examples
cakephphas-manybelongs-to

How create belonge assocation in models in cakephp


I use Cakephp framework, and I have problem with my association. How create belong to association in models in cake php. When I use belongto and hasMany in my model.

Can I find sample model to view this example?


Solution

  • Simple belongsTo association:

    <?php
    class Profile extends AppModel {
    var $name = 'Profile';                
    var $belongsTo = array(
        'User' => array(
            'className'    => 'User',
            'foreignKey'    => 'user_id'
        )
    );  
    }
    ?>
    

    Simple hasMany association:

    <?php
    class User extends AppModel {
    var $name = 'User';                
    var $hasMany = array(
        'Comment' => array(
            'className'     => 'Comment',
            'foreignKey'    => 'user_id',
            'conditions'    => array('Comment.status' => '1'),
            'order'    => 'Comment.created DESC',
            'limit'        => '5',
            'dependent'=> true
        )
    );  
    }
    ?>
    

    More specific information about associations is in the CakePHP Book.