代码之家  ›  专栏  ›  技术社区  ›  Tijme

Cakephp有一个模型和一个属于多个模型

  •  0
  • Tijme  · 技术社区  · 12 年前

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

    示例情况

    桌子 用户

    id
    organisation_id
    

    桌子 组织

    id
    name
    

    桌子 用户组织权限

    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解决方案?

    1 回复  |  直到 12 年前
        1
  •  0
  •   Tijme    12 年前

    答案实际上在CakePHP2.x Cookbook中。

    同一模型的多个关系

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

    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

    推荐文章