如何使用laravel访问另一个表的外键值

时间:2016-05-16 04:57:27

标签: laravel laravel-5 laravel-5.1 laravel-5.2

我创建了一个自定义数据透视模型,它是具有id,section_id和subject_id的SectionSubject。我现在想要访问与section_id相关的其他值。这是我的Sectionsubject模型和section_subject表:

SectionSubject.php

class SectionSubject extends Model
{
    protected $table = 'section_subject';

    public function students()
    {
        return $this->belongsToMany(Student::class, 'section_subject_student','section_subject_id'
            )->withTimestamps();
    }

    public function assignStudents(Student $student)
    {
        return $this->students()->save($student);
    }

}

create_section_subject.php

Schema::create('section_subject', function (Blueprint $table) {
  $table->increments('id');
  $table->integer('section_id')->unsigned();
  $table->integer('subject_id')->unsigned();
  $table->string('schedule')->unique();
  $table->string('room_no');

  $table->foreign('section_id')
     ->references('id')
     ->on('sections')
     ->onDelete('cascade');

  $table->foreign('subject_id')
     ->references('id')
     ->on('subjects')
     ->onDelete('cascade');
});

现在我想获取这些值并将其放在我的ReservationController上。我尝试使用一对多的关系,但似乎无法正常工作。

class ReservationController extends Controller
{

    public function index()
    {
        $sectionSubject = SectionSubject::find(1);

        //code here
        return view('reservation.form', compact('sectionSubject');
    }

} 

1 个答案:

答案 0 :(得分:0)

你可以通过这样做来获取关系

$sectionSubject = SectionSubject::with('students')->find(1);

//print your variable
echo "<pre>";
 print_r($sectionSubject->toArray());
echo "</pre>";

您将找到相关的表格数据