蛋糕php使用表关系

时间:2010-02-06 09:12:38

标签: database cakephp model controller relationship

是否使用像

这样的创作关系
 var $belongsTo = array(
        'UserType' => array(
            'className' => 'UserType',
            'foreignKey' => 'user_type_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );
    //The Associations below have been created with all possible keys, those that are not needed can be removed
    var $hasMany = array(
        'UserOpenid' => array(
            'className' => 'UserOpenid',
            'foreignKey' => 'user_id',
            'dependent' => true)
);

如果我在“hasMany”中添加了一个在“belongsTo”意义上创建的表格怎么办? 发生任何错误。 蛋糕如何使用模型中指定的关系?

2 个答案:

答案 0 :(得分:1)

通过将模型关联在一起,您可以告诉CakePHP在使用find()函数时从数据库中获取什么。例如:

posts BelongsTo users =当您检索帖子时,您还会获得有关此帖子所属用户的数据(posts.user_id = users.id)。

答案 1 :(得分:0)

除了Paweł的回答:

“belongsTo”,“hasMany”等只是选择的术语,用于反映数据库的设计方式以及表格如何相互关联,这决定了数据的检索方式。

  • belongsTo表示一对多的关系,“归属”模型位于“很多”方面
  • hasMany表示一对多关系的另一面
  • hasOne表示一对一的关系
  • hasAndBelongsToMany表示多对多关系

特定关系确定哪个表包含哪个外键以及如何JOIN表自动检索数据。如果您对此没有经验,请查看Normalization