通过id从另一个表获取价值

时间:2019-04-04 11:36:36

标签: database laravel

我是laravel的新手。我有一张桌子:

  

students_attendance

students_attendance中,有一个名为class_id的列,它引用students_classes表,其中还包括每个学生的class_idclass_name

在前端表中,我从students_attendance表中获取值,因此class_id可用,但是我需要的是class_name

我如何获得class_name

//为学生出勤而迁移

 public function up()
    {
        Schema::create('students_attendances', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('class_id')->index()->unsigned()->nullable();
            $table->string('student_id');
            $table->string('first_name');
            $table->string('last_name');
            $table->string('attendance');
            $table->timestamps();
        });
    }

//为students_classes迁移

 public function up()
    {
        Schema::create('students_classes', function (Blueprint $table) {
            $table->increments('id');
            $table->string('class_name');
            $table->string('class_fee');
            $table->string('class_teacher');
            $table->timestamps();
        });
    }

//学生课堂模型

class StudentsClass extends Model
{
    protected $fillable = [
        'class_name',
        'class_fee',
        'class_teacher'
    ];

    public function students() {
        return $this->hasMany('App\Students');
    }

}

//学生出勤模式

class StudentsAttendance extends Model
{
    protected $fillable = [
        'class_id',
        'student_id',
        'first_name',
        'last_name',
        'attendance'
    ];

    public function studentsClass() {
        return $this->belongsTo('App\StudentsClass');
    }

}

1 个答案:

答案 0 :(得分:0)

通过StatusAttendance变量,您可以使用$attendance->studentClass->class_name访问类名。

假设您拥有class_id,并且想要获取关联类的名称,则只需执行以下操作:

$class = StudentsClass::find($class_id);
$class->class_name; // Outputs the name