Reputation: 51
I have two Model, School, and Student the relationship is, School has Many Student //Student Model
public function school()
{
return $this->belongsTo('App\School');
}
and same in School Model the following is the function for relationship
public function student()
{
return $this->hasMany('App\Student');
}
Now I have a show Page I like to display the following information. (school_name,school_code) from the school table and student information all from the Student Table.using show function in student controller if I pass as
public function show($id)
{
$student=Student::find($id);
$school=School::find($id);
return View::make('student.show')->with(['school'=> $school,'student'=>$student]);
}
it gets data from school if school_id ==$id but one school has many students it fails if I click to show a button with an ID of 109, how to write the Join query to get school_code and school_name from schools table.
Upvotes: 0
Views: 1513
Reputation: 733
Since you have the relationship setup already, you could use Eloquent to fetch data for single student with the school that he belongs tos as follow:
public function show($id)
{
$student = Student::with('school')->where('id', $id)->first();
return View::make('student.show')->compact('student);
}
Now you can retrieve data show.blade.php
as follow:
@foreach($student as $stud)
<li> {{ $stud->student_name}}</li>
<li> {{ $stud->student_code}}</li>
<li> {{ $stud->->school->school->name}}</li>
<li> {{ $stud->school->school_name }}</li>
@ndforeach
Upvotes: 0
Reputation: 643
Not sure why you are using the same $id
to getting student and school
public function show($id)
{
$student = Student::find($id);
$school = $student->school; //school of the student
return View::make('student.show')->with(['school'=> $school,'student'=>$student]);
}
Use this code
Upvotes: 2
Reputation: 5270
Your model should be like this
public function students()
{
return $this->hasMany('App\Student');
}
You have to change like this.
$student = Student::find($id);
$school = $student->school;
Upvotes: 0