How create belonge assocation in models in cakephp

2019-08-20 02:05发布

问题:

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?

回答1:

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.



回答2:

  1. User has Many Photos
  2. Photos belongs to User

In User Model :

var $hasMany = array(
    'Photo' => array(
        'className' => 'Photo',
        'foreignKey' => 'user_id'
);

In Photo Model :

var $belongsTo = array(
    'User' => array(
        'className' => 'User',
        'foreignKey' => 'user_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ),
    'PhotoAlbum' => array(
        'className' => 'PhotoAlbum',
        'foreignKey' => 'photo_album_id',
        'conditions' => '',
        'fields' => '',
        'order' => '',
    ))