【问题标题】:Join 3 tables in Yii 2在 Yii 2 中加入 3 个表
【发布时间】:2017-04-24 17:30:48
【问题描述】:

我正在开发一个 Yii 2 项目。我有 3 张桌子:

1) 学生数据表

  • student_data_id
  • 姓氏
  • 名字

2) 学生表

  • student_id
  • student_data_id
  • class_id

3) 成绩表

  • student_id

从分数表中,我需要访问学生的姓名。换句话说,我需要使用 student_id 从学生数据表中检索学生的姓氏和名字。我熟悉加入表格,但我不知道如何在 Yii2 中从语法上做到这一点。我希望我很清楚,并提前谢谢你。

编辑 我每张桌子也有 3 个模型。

【问题讨论】:

    标签: sql database join yii2


    【解决方案1】:

    Scores 模型中,创建以下关系:

    public function getStudentData() {
        return $this->hasOne(StudentData::className(), ['student_data_id' => 'student_data_id'])
            ->viaTable('student', ['student_id' => 'student_id']);
    }
    

    【讨论】:

    • 先生那里的Filter是什么意思?是模特吗?
    • 抱歉,我从示例中提取了代码,但忘记更改了。已更新。
    • 我明白您回答的逻辑,先生。但是我在 score.student_id 上遇到了未知属性错误
    • 你的表叫scores吗?这个字段叫student_id吗?
    • 是的,先生。我确信命名。我还对拼写进行三重检查。根据答案的逻辑,它应该是正确的。语法可能有问题
    猜你喜欢
    • 1970-01-01
    • 2016-11-16
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    • 2016-12-08
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多