2013-10-30 118 views
4

我需要根據不是主鍵的字段創建關係。許多如何做到這一點的例子都基於一對多和多對多的關係。我試圖從下面的建議沒有成功使用除主鍵以外的字段的Yii模型關係

Relation in YII with not "ID" as primary key

Yii CActiveRecord: find related data, but not using the primary key

Yii Relations with non-Primary keys

Yii Model Relation Join (HAS_ONE)

我有以下表結構:

+------+---------+-----------+ 
| id | name | status_id | 
+------+---------+-----------+ 
| 1 | service1| 1   | 
+------+---------+-----------+ 
| 2 | service2| 2   | 
+------+---------+-----------+ 

這是我的表active_service。我也有如下表

+----------+----------+---------------------+-----------+ 
|id  |related_id|related_text   | text  | 
+----------+----------+---------------------+-----------+ 
|65  |1   |ActiveServices_status| Open  | 
+----------+----------+---------------------+-----------+ 
|72  |2   |ActiveServices_status| Active | 
+----------+----------+---------------------+-----------+ 
|102  |3   |ActiveServices_status| Closed | 
+----------+----------+---------------------+-----------+ 

這是我related_fields表 此表保存用於下拉等related_text告訴我們什麼是對的各個領域和related_id是地位的ID,這是我需要鏈接到的領域。因此,active_service表中的status_id涉及條件滿足的related_fields表的related_id字段,即related_text設置爲ActiveServices_status。我將如何去創造這種關係。這是迄今爲止我所做的最好的例子(在ActiveServices模型中)。

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(

     'rl_status'=>array(self::BELONGS_TO,'RelatedFields','status_id','condition'=>'related_text = "ActiveServices_status"','on'=>'status_id = related_id'), 
    ); 
} 

任何幫助,將不勝感激。

+0

爲什麼要使用主鍵以外的其他設置關係?如果有兩行status_id = 1,會發生什麼情況? – Pitchinnate

+0

你有'狀態'表嗎? – Pitchinnate

+0

@Pitchinnate狀態保存在相關字段表中。如果有兩個狀態爲1的活動服務,則該關係會將它們都顯示爲「打開」。這裏不會有衝突。表中還有一些其他領域我沒有列入,因爲它們對於這個特定的問題並不重要。例如,在活動服務中,有一個account_id字段與賬戶表相關。這樣我可以找到所有服務並在帳戶上顯示它們,在引用其狀態時使用'echo rl_status'。我發佈了我在 –

回答

12

因此,最終在嘗試了大約100個不同的代碼行之後纔想出了這件事。所以繼承人爲我工作的解決方案。

'rl_status' => array(self::BELONGS_TO, 'RelatedFields', '', 'foreignKey' => array('status_id'=>'related_id'),'condition'=>'related_text = "ActiveServices_status"', 
+0

下找到的解決方案,謝謝,它對我有很大的幫助 –

1

備案,在Yii 1.1.9中已解決;見問題#2706。從文檔來看,這並不是非常明顯,但可以通過將數組放置在外鍵名稱的正常位置,將本地列作爲鍵和外鍵列作爲值來實現。例如,如果您有兩個本地列'fk1'和'fk2'引用模型爲「Foo」的表中的列'col1'和'col2'的組合唯一鍵,那麼您在關係中的條目數組是這樣的:

'foo' => array(self::BELONGS_TO, 'Foo', array('fk1'=>'col1','fk2'=>'col2'))

從文檔中引用的CActiveRecord.relations()

如果你需要指定自定義PK-> FK關聯,你可以把它定義爲陣列(「FK」 => 'pk' 中)。

1
'rl_status' => array(self::BELONGS_TO, 'RelatedFields', '', 'foreignKey' => array('status_id'=>'related_id'),'condition'=>'related_text = "ActiveServices_status"'