php – 使用主键以外的字段的Yii模型关系

前端之家收集整理的这篇文章主要介绍了php – 使用主键以外的字段的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'),);
}

任何帮助,将不胜感激.

最佳答案
因此,在尝试了大约100行不同的代码后,最终想出了这个问题.因此,这是对我有用的解决方案.

'rl_status' => array(self::BELONGS_TO,'','foreignKey' => array('status_id'=>'related_id'),

猜你在找的MySQL相关文章