Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...