1

Application_Model_User在 Datamapper 中设计关系时,必然会将关系称为与相关对象同名的关系,当您有类似类名之类的东西时,这不太方便。对于那些急于说有一个带有“class”键的配置选项的人,我知道。去过那里试过。它仅适用于获取相关对象,不适用于更新它们。

这是重现问题的代码片段:

// User Model
class UserModel extends Datamapper
{
    public $table = 'users';
    public $has_many = array(
        'roles' => array(
            'class' => 'RoleModel',
            'other_field' => 'usermodel',
            'join_other_as' => 'role',
            'join_self_as' => 'user',
            'join_table' => 'users_roles' 
        ),
    );
}

class RoleModel extends DataMapper
{
    public $table = 'roles';
    public $has_many = array(
        'usermodel' => array('class'        => 'UserModel',
                         'other_field'  => 'roles',
                         'join_other_as'=> 'user',
                         'join_self_as' => 'role',
                         'join_table'   => 'users_roles' )
    );
}

// controller code. Make sure you have a role with INT id = 2, and a user with INT id = 5 in your db
$user = new UserModel(2);
$role = new RoleModel(5);
$user->save($role);

此代码给出“无法将用户模型与角色模型相关联”。user_roles错误,但是如果将关系从“roles”重命名为“rolemodel” ,它确实可以正常工作(意味着在连接表中插入了一条新记录)。

所以,如果有任何 CI 的 Datamapper 的狂热用户可以提供帮助,请告诉我如何正确定义关系。

4

1 回答 1

2

更新

您可以使用关系键将对象保存为关系:

$object->save( $related, $relationship_key ). 

所以你需要使用

$user->save($role, "roles");

请参阅此网页的底部:http: //datamapper.wanwizard.eu/pages/save.html


留下这一点以防它帮助别人。

看起来您想在关系上使用自定义名称。(这就是我在经历了所有的愤世嫉俗之后得到的)-

您可以使用关系数组中的键为关系命名任何您想要的名称。因此,在下面的代码片段中,您使用book<- 这必须或不必与类同名- 这就是class密钥的用途。

class Author extends DataMapper {
  $has_many = array(
    'book' => array(  // YOU USE THIS KEY TO NAME THE RELATIONSHIP
        'class' => 'book',
        'other_field' => 'author',
        'join_self_as' => 'author',
        'join_other_as' => 'book',
        'join_table' => 'authors_books'
     )
  );
}

如果这对你不起作用,我猜你在建立关系时还有其他问题。

http://datamapper.wanwizard.eu/pages/advancedrelations.html

于 2012-01-03T14:47:42.683 回答