【问题标题】:Yii Framework Database RelationshipYii 框架数据库关系
【发布时间】:2012-05-28 08:38:46
【问题描述】:

我在定义类关系时遇到问题。

在此之前,让我展示一下我的数据库结构

    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".

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

【问题讨论】:

    标签: php activerecord yii


    【解决方案1】:

    agent->views 不是BELONGS_TO 关系。要么是HAS_ONE,要么是HAS_MANY

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

    【讨论】:

    • 但我无法使用以下内容显示数据: $obj) { print_r( $obj->views ); } ?>
    • 你的意思是不能?如果它是空的,可能你的视图表中没有相关数据。
    【解决方案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();
    

    在这个 $model 你有所有的视图记录和代理..

    希望这对你有用..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-16
      相关资源
      最近更新 更多