I'm writing a ajax call to a controller with a function to return $courses
I have two tables/Models... Courses and Instructors.
Instructor has...
public function Courses()
{
return $this->hasMany('App\Course');
}
Courses has...
public function Instructor()
{
return $this->belongsTo('App\Instructor');
}
I have a query that's working but would like to know how to write it the eloquent way...
This works.
$courses = \App\Course::where('SemesterID', $id)->join('Instructors', 'somascourses.Instructor_id', '=', 'Instructors.id')->get();
This gives me an error not understanding the ::with.....
//$courses = \App\Course::where('SemesterID', $id)::with('Instructor')->get();
Sorry... A couple of more questions.
Should I be writing these as functions in the Model ? Or is it ok in the controller?
How do I bring over only specific fields from the instructors table in the query?
There are no 'rules' about where you should be putting the functions. Personally, if it is just a single line of code then putting in the Controller is ok. Anything more and I would start considering extracting.
To get specific columns do this:
\App\Course::where('SemesterID', $id)::with('Instructor:column1,column2')->get();
It returns all the fields from instructors table. I could not get any of the others to work and return the fields. I would love to be able to only return a few of the fields.
Anyone????
Eloquent relationships are probably not working for you since you don't follow convention for key names, and have not specified the columns to use in the relationship.