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

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

问题描述

在用户模型中:

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

在照片模型中:

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

这里一位用户有很多照片.所以我的问题是这里的别名是所有者",这让我清楚地理解用户"的确切含义,但这是使用别名的唯一原因吗?它会影响用户模型中的照片"吗?或者如何在/by cakephp 中使用所有者"?

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.同一模型的多个外键

例如,您的 photos 表有两个字段: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天全站免登陆