what is CakePHP model alias used for?

后端 未结 2 1946
我寻月下人不归
我寻月下人不归 2020-12-16 17:49

In user model:

var $hasMany = array(
        \'Photo\' => array(
            \'className\' => \'Photo\',
            \'foreignKey\' => \'owner_id\',         


        
相关标签:
2条回答
  • 2020-12-16 18:32

    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.

    0 讨论(0)
  • 2020-12-16 18:32

    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.

    0 讨论(0)
提交回复
热议问题