How create belonge assocation in models in cakephp

元气小坏坏 提交于 2019-12-13 04:05:06

问题


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' => '',
    ))


来源:https://stackoverflow.com/questions/7703992/how-create-belonge-assocation-in-models-in-cakephp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!