dimanche 15 mai 2016

How to access the values of a foreign key of another table using laravel

I created a custom pivot model which is SectionSubject that have an id, section_id and subject_id. I want now to access the other values related to the section_id. Here is my Sectionsubject model and section_subject table:

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');
});

Now I want to fetch those values and place it on my ReservationController. I tried to use one to many relationship but it seems not working.

class ReservationController extends Controller
{

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

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

} 



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire