【问题标题】:How to get data using yii2 active records and relations?如何使用 yii2 活动记录和关系获取数据?
【发布时间】:2016-08-29 20:44:21
【问题描述】:

我有下面的代码不能按预期工作。

模型中指定的关系:

 public function getShift() {
      return $this->hasOne(Shift::className(), ['id' => 'shift_id']); 
}

public function getShiftName() {
    return $this->shift->name;
}

查询:

$job_position = JobPositions::find()
            ->innerJoinWith(['shift'])
            ->where('month(date) = month(curdate())')
            ->one();

它给了我关于 job_position 表而不是 shift 表的数据。如何获取班次表的数据?

【问题讨论】:

    标签: activerecord yii2 relationship


    【解决方案1】:

    你应该简单地使用$job_position->shift,它会返回相关的Shift对象。

    您还应该阅读以下内容:Accessing Relational Data

    当您通过 getter 方法 getXyz() 声明名为 xyz 的关系时,您将能够像访问对象属性一样访问 xyz。请注意,名称区分大小写。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-23
      相关资源
      最近更新 更多