Yii与非主键的关系

时间:2011-12-14 18:06:40

标签: php yii

我有一个mysql表和一个mysql视图我正在尝试建立关系。

表格(commissions)如下:

--commissions--
id(primary Key)
date_added
order_id
salesrep_id
customer_id
commission_total
status

视图(rep_view_customer)如下:

--rep_view_customer--
entity_id
email
first_name
last_name
company

我正在尝试将rep_view_customercommissions commissions.customer_id = rep_view_customer.entity_id联系起来。

我尝试过使用on选项:

'rep_view_customer' => array(self::HAS_ONE, 'RepViewCustomer', '', 'on'=>'rep_view_customer.entity_id = t.customer_id')

我还尝试使用以下方法设置rep_view_customer模型的主键:

public function primaryKey(){
    return 'entity_id';
}

但我似乎总是遇到类似于:

的错误
  

CDbCommand无法执行SQL语句:SQLSTATE [42S22]:   未找到列:1054未知列't.customer_id'在'where   条款'。执行的SQL语句是:SELECT   rep_view_customerentity_id AS t1_c0,   rep_view_customeremail AS t1_c1,   rep_view_customerfirst_name AS t1_c2,   rep_view_customerlast_name AS t1_c3,   rep_view_customercompany AS t1_c4 FROM rep_view_customer   rep_view_customer WHERE(rep_view_customer.entity_id =   t.customer_id)

我的智慧结束了接下来的尝试

2 个答案:

答案 0 :(得分:0)

您必须在repview_customer中创建一个与委托相关的外键。仅使用主键,您将无法完成此操作。

答案 1 :(得分:0)

我是这样做的,它有效: 所以在你设置的佣金模型中:(它在模型中通过自身进行关系,然后连接输出将与正常关系相同,但在佣金模型中使用其他唯一键)

public function relations()
    {
        return array(
            'commission' => array(self::HAS_ONE, 'Commission', 'entity_id', 'on' => 'commission.customer_id=rep_view_customer.entity_id'),
            'rep_view_customer' => array(self::HAS_MANY, 'RepViewCustomer', '', 'through' => 'commission', 'condition' => '...'),
        ),
    }