【问题标题】:Cakephp hasOne Model and hasAndBelongsToMany ModelCakephp hasOne 模型和 hasAndBelongsToMany 模型
【发布时间】:2014-08-11 17:10:27
【问题描述】:

我在 CakePHP 2.x 中的 CakePHP belongsTo 和 hasAndBelongsToMany 关系有问题

示例情况

用户

id
organisation_id

组织

id
name

user_organisation_permissions

id
user_id
organisation_id

用户模型

hasAndBelongsToMany(Organisation);
belongsTo(Organisation)

一个用户属于一个组织,但拥有多个组织的权限,导致如下冲突:

$aUser = $this->User->findById(1);
print_r($aUser);

// Output

# With the belongsTo relation
array(
    'User' => array(
        'id' => 1,
        'organisation_id' => 1
        'name' => 'Test User'
    ),
    'Organisation' => array(
        'id' => 1,
        'name' => 'Test organisation'
    )
);

# With the hasAndBelongsToMany relation
array(
    'User' => array(
        'id' => 1,
        'organisation_id' => 1
        'name' => 'Test User'
    ),
    'Organisation' => array(
        1 => array(
            'id' => 1,
            'name' => 'Test organisation'
        ),
        2 => array(
            'id' => 1,
            'name' => 'Test organisation'
        )
    )
);

# When both relations are enabled it doesn't work

有人有解决这个冲突的办法吗?

对于这种冲突是否有“本机”CakePHP 解决方案?

【问题讨论】:

  • 您指的是什么“冲突”? ps,请务必提及您的确切 CakePHP 版本!
  • 好的,我补充了一些解释。
  • @ndm 所以在他们展示的第一个例子中,发件人和收件人就像“虚拟”模型?
  • 嗯,根据您所说的“虚拟”的含义,您可能可以这样称呼它,虽然实际上并没有进行任何虚拟化,但它就像将一个对象的引用一分为二存储一样虚拟具有不同名称的变量。 SenderRecipient 只是别名,将用于代替实际的型号名称。

标签: php cakephp relationship cakephp-model


【解决方案1】:

答案实际上在 CakePHP 2.x Cookbook 中。

同一模型的多个关系

在某些情况下,一个模型与另一个模型有多个关系。例如,您可能有一个 Message 模型,它与 User 模型有两种关系:一种是与发送消息的用户的关系,另一种是与接收消息的用户的关系。消息表将有一个字段 user_id,还有一个字段 recipient_id。现在你的 Message 模型看起来像这样:

class Message extends AppModel {
    public $belongsTo = array(
        'Sender' => array(
            'className' => 'User',
            'foreignKey' => 'user_id'
        ),
        'Recipient' => array(
            'className' => 'User',
            'foreignKey' => 'recipient_id'
        )
    );
}

来源:http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#multiple-relations-to-the-same-model

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 2023-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    相关资源
    最近更新 更多