【问题标题】:Yii Relations ModelYii 关系模型
【发布时间】:2015-02-12 14:00:13
【问题描述】:

在以下情况下尝试设置关系时我遇到了麻烦。

我有一张桌子Person (id_person, name, id_mother, id_father)

我知道在模型中与不同表的外键建立关系很热。但在这种情况下,id_mother 和 id_father 映射到其他 id_person(希望我说清楚了)。

这是我尝试过的

 public function relations() {
     return array(
            'father'=>array(self::BELONGS_TO, 'PERSON', 'id_person'),
            'mother'=>array(self::BELONGS_TO, 'PERSON', 'id_person'),
     );
}

我想要他们在 CGridVew 中的名字

$data->father->NAME
$data->mother->NAME

在这种情况下我该怎么办?

【问题讨论】:

  • 在这种情况下你有延迟加载。尝试将属性纳入标准或将属性设置为 true ('father'=>array(self::BELONGS_TO, 'PERSON', 'id_person', 'together'))。您也可以使用: $data->father ? $data->father->NAME : '';
  • 一起工作,但是当 id_mother 和 id_father 为空时我该怎么办?它说关系 0 没有定义
  • 然后测试 if (isnull($data->father->NAME)) ....

标签: yii relation cgridview


【解决方案1】:

我认为你定义了错误的关系。 关系方法应该是这样的:

public function relations() {
     return array(
            'father'=>array(self::BELONGS_TO, 'PERSON', 'id_father'),
            'mother'=>array(self::BELONGS_TO, 'PERSON', 'id_mother'),
     );
}

希望对你有帮助。

【讨论】:

  • 它不起作用,因为 id_father 和 id_mother 就像 id_person 的外键。但他们都在同一张桌子上。在这种情况下,我想要他们的名字
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多