Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 712
user518261 Avatar asked Nov 25 '10 08:11

user518261


2 Answers

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.

like image 166
RabidFire Avatar answered Nov 10 '22 04:11

RabidFire


It allows you to do things like $this->Owner->read(null,$userId); You can have an OwnersController and views/owners.

It is ... an alias. In a sense, User is an alias for the db table users.

A better example: I have a CMS where I use the table articles for Article, BlogItem and News. Those three names are aliases for the same table that allow me to set up different models, relationships and behaviour. So I have a BlogItemsController and a NewsController as well as an ArticlesController.

like image 23
Leo Avatar answered Nov 10 '22 04:11

Leo