【问题标题】:How to put data from multiple tables into one model?如何将多个表中的数据放入一个模型中?
【发布时间】:2012-01-12 02:39:29
【问题描述】:

如何制作模型,连接数据库中的三个表?我的数据库结构是:

  • 用户
    • 身份证
    • 其他字段
  • users_info
    • 身份证
    • users_id - 'users' 表的外键
    • 其他字段
  • users_credentials
    • 身份证
    • users_id - 'users' 表的外键
    • 其他字段

以前,我想在一个模型中绑定 2 个表,所以我使用了 addRelatedEntity 方法。这是我的代码:

class Model_UserInfo extends Model_Table{
    public $entity_code = 'user_info';
    function init(){
        parent::init();
        $this->addField('phone')->caption('Nr tel');
        $this->addField('users_id');
    }
    function addRelation(){
        $this->addRelatedEntity('i','users','users_id','left outer');
    }

}

然后我在其他文件中扩展它-

class Model_User extends Model_UserInfo{
    function init(){
        parent::init();
        parent::addRelation();

        $this->newField('name')->caption('Imie')->mandatory(true)->relEntity('i','name');
    }

}

而且效果很好。但是,如果我想将 3 个表绑定到一个模型中怎么办?我不能扩展 2 个类。有没有办法在 Model_User 中使用 addRelatedEntity,并引用 Model_UserInfo 和 Model_Credentials?

【问题讨论】:

  • 调用父级::addRelation();就面向对象编程而言,这不是一个好方法。 $this->addRelation();更好的是,如果函数没有在当前类中定义,它是从父类继承的,所以它的工作方式完全相同。只是想指出这一点。

标签: atk4


【解决方案1】:

您可能需要反转联接并从由其他 2 个表联接的“用户”表开始,尽管只要您获得正确的查询,这并不重要。

首先,将$this->debug(); 添加到模型的初始化中。当您将调试连接、更新等时,这将对您有很大帮助。

class Model_User extends Model_Table {
    public $entity_code='users';
    function init(){
        parent::init();
        $this->newField('name')
            ->caption('Imie')
            ->mandatory(true);
    }
}

class Model_User_Combined extends Model_User {
    function init(){
        parent::init();

        $this->addRelatedEntity('info','users_info','inner','related');
        $this->addRelatedEntity('cred','users_credentials','inner','related');

        $this->addField('phone')->caption('Nr tel')->relEntity('info');
        $this->addField('password')->caption('Parol')->relEntity('cred');
    }
}

与您现在拥有的解决方案相比,这使用“用户”作为主表并将附加表作为“相关”连接。

您还将受益于继承,Model_User 将为您添加一些基本的用户字段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    • 2018-03-11
    • 1970-01-01
    • 2013-11-08
    • 2013-04-10
    • 1970-01-01
    相关资源
    最近更新 更多