什么是CakePHP模型别名用于? [英] what is CakePHP model alias used for?

查看:192
本文介绍了什么是CakePHP模型别名用于?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用者模式中:

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

在照片模型中:

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

这里有一个用户有很多照片。
所以我的问题是,这里的别名是'Owner',这让我明确了解'User'的确切含义,但这是唯一的理由使用别名?它是否影响用户模型中的照片?或者如何使用cakephp中的Owner?

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!

推荐答案

别名的两个有用方案:

1。多个外键指向同一个模型

例如,您的照片表有两个字段: code> created_user_id & modified_user_id

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。创建特定于您应用程序域的逻辑词

使用数组中的条件字段,您可以指定不同类型的模型:

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),
        ...
    ),
);

在上述示例中,Group模型具有不同种类的用户(已批准,未批准和已删除)。使用别名有助于使您的代码非常优雅。

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

这篇关于什么是CakePHP模型别名用于?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆