Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

what is CakePHP model alias used for?

In user model:

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

In photo model:

var $belongsTo = array(
        'Owner' => array(
            'className' => 'User',
            'foreignKey' => 'owner_id',
            ...
            ),
);

Here one user has many photos. So what my question is that here the alias name is 'Owner', which make me clear to understand the exact meaning of 'User', but is this the only reason to use alias? does it affect 'Photo' in user model? or how to use 'Owner' in/by cakephp?

I don't quite understand the meaning of alias in model. Appreciate your help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Two useful scenarios for aliases:

1. Multiple foreign keys to the same model

For example, your photos table has two fields: created_user_id & modified_user_id

var $belongsTo = array(
    'CreatedUser' => array(
        'className' => 'User',
        'foreignKey' => 'created_user_id',
        ...
    ),
    'ModifiedUser' => array(
        'className' => 'User',
        'foreignKey' => 'modified_user_id',
        ...
    ),
);

2. Creating logical words specific to your application's domain

Using the conditions field in the array, you could specify different kinds of models:

var $hasMany = array(
    'ApprovedUser' => array(
        'className' => 'User',
        'foreignKey' => 'group_id',
        'conditions' => array(
            'User.approved' => 1,
            'User.deleted'  => 0
        ),
        ...
    ),
    'UnapprovedUser' => array(
        'className' => 'User',
        'foreignKey' => 'group_id',
        'conditions' => array(
            'User.approved' => 0,
            'User.deleted'  => 0
        ),
        ...
    ),
    'DeletedUser' => array(
        'className' => 'User',
        'foreignKey' => 'group_id',
        'conditions' => array('User.deleted'  => 1),
        ...
    ),
);

In the above example, a Group model has different kinds of users (approved, unapproved and deleted). Using aliases helps make your code very elegant.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...