Yii框架数据库关系

时间:2012-05-28 08:38:46

标签: php activerecord 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(
        'agents' => array(self::BELONGS_TO, 'Agent', '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(
        'groups'=>array(self::BELONGS_TO, 'Group', 'group_id'),
        'views' => array(self::BELONGS_TO, 'View', '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 个答案:

答案 0 :(得分:2)

代理 - >视图不是BELONGS_TO关系。它是HAS_ONEHAS_MANY

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

答案 1 :(得分:-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();

在这个$模型中,您拥有所有视图记录和代理..

希望这对你有用..