如何制作连接数据库中三个表的模型?我的数据库结构是:
以前,我想在一个模型中绑定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?
答案 0 :(得分:1)
您可能需要反转连接并从其他2个表连接的“user”表开始,尽管只要您获得正确的查询就没那么重要。
首先,将$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');
}
}
与您现在使用的解决方案相比,它使用“users”作为主表,并将其他表连接为“相关”。
此外,您将从继承中受益,Model_User
将为您添加一些基本用户字段。