2012-05-28 81 views
1

我在定义类关系时遇到了问题。Yii框架数据库关系

在此之前,让我告诉你我的数据库结构

Agent table 
    id 
    username 
    password 

    Views table 
    id 
    agent_id 
    accessor_id 

代理可以让很多代理商以查看他们的帖子。表视图保存代理人所有者和允许查看他/她发布的代理的数据。

在视图模型我的关系声明声明如下:

/** 
* @return array relational rules. 
*/ 
public function relations() { 
    // NOTE: you may need to adjust the relation name and the related 
    // class name for the relations automatically generated below. 
    return array(
     'groups'=>array(self::BELONGS_TO, 'Group', 'group_id'), 
     'views' => array(self::BELONGS_TO, 'View', 'agent_id'), 
    ); 
} 

我收到以下错误,当我试图运行:在代理模式

/** 
* @return array relational rules. 
*/ 
public function relations() { 
    // NOTE: you may need to adjust the relation name and the related 
    // class name for the relations automatically generated below. 
    return array(
     'agents' => array(self::BELONGS_TO, 'Agent', 'agent_id'), 
    ); 
} 

我的关系声明声明如下应用程序。

The relation "views" in active record class "Agent" is specified with an invalid foreign key "agent_id". There is no such column in the table "agents". 

我该如何解决这个问题?请帮忙。谢谢!

回答

2

agent-> views不是BELONGS_TO的关系。它要么HAS_ONEHAS_MANY

'views' => array(self::HAS_ONE, 'View', 'agent_id'), 
+0

但我无法用下面显示的数据: $ obj){print_r($ obj-> views); }?> –

+0

你是什么意思?如果它是空的,可能你只是在视图表中没有相关的数据。 –

-2

如果您需要定义仅视图模型关系......

public function relations() { 
    // NOTE: you may need to adjust the relation name and the related 
    // class name for the relations automatically generated below. 
    return array(
     'agents' => array(self::BELONGS_TO, 'Agent', 'agent_id'), 
    ); 
} 

而且也没有必要定义代理模式的关系..

在控制器端你可以找到像这样的记录...

$model = View::model()->with('agents')->findAll(); 

在您的视图中的所有记录,并同时代理这$模型..

希望这会为你工作..