Laravel Model Relationship between Students and Courses - laravel

I have a Model Student and Course.
Here's what I am trying to get from those models,
Every student is enrolled to one course and the way I save it to the database is like below,
Student Info..., course_id... <- which is basically taken from the Courses table
I want to retrieve the Course name since I already have the course_id stored in the Students table.
I designed the model like:
//Course Model
class Course extends Model
{
public function student(){
return $this->belongsToMany('App\Student');
}
}
//Student Model
class Student extends Model
{
public function course(){
return $this->hasOne('App\Course');
}
}
But I don't know how to or what to do next, I am really new to Eloquent approach.
Need help.
I tried to retrieve the Course name using the code below :
$students = Student::all();
#foreach($students as $student)
$student->course->name
....
but I think it is wrong, I'm only getting an error about unknown column

Instead of using belongsToMany for student relation in Course.php model,
Use hasMany function like:
//Course Model
class Course extends Model
{
public function student(){
return $this->hasMany('App\Student');
}
}
//Student Model
Since, student belongs to course, you should use belongsTo instead of hasOne
class Student extends Model
{
public function course(){
return $this->belongsTo('App\Course');
}
}
In order to optimize the query for retrieving all related courses, you can use with Eagar Loading relationship like:
$students = Student::with('course')->all();
#foreach($students as $student)
//If incase there are no course related to the student
$student->course->name ?? null
....

Previous Code :
//Course Model
class Course extends Model
{
public function student(){
return $this->belongsToMany('App\Student');
}
}
//Student Model
class Student extends Model
{
public function course(){
return $this->hasOne('App\Course');
}
}
Replace with :
//Course Model
class Course extends Model
{
public function students(){
return $this->hasMany(Student::class); // '\App\Student' also ok
}
}
//Student Model
class Student extends Model
{
public function course(){
return $this->belongsTo(Course::class);
}
}
Why belongsTo at Student Model ?
Inside : When a table primary key assign in another table as foreign key then you should add belongsTo this assigning table.
Here Courses table primary id assigned as foreign key at Students table

Related

ManytoMany Relation between 3 tables Laravel

I have 3 tables with Models all belongToMany related with each other:
Batchyear
Grade
Student
A student may attend many batchyears, and will be have many grades, and each grade have many students.
How to get the relationship via Eloquent so that a student is in a certain grade in a certain batchyear?
class Batch extends Model
{
public $guarded = [];
public function students()
{
return $this->belongsToMany(Student::class);
}
public function grades()
{
return $this->belongsToMany(Grade::class);
}
}
and here is grade
class Grade extends Model
{
public $guarded = [];
public function students()
{
return $this->belongsToMany(Student::class);
}
public function batches(){
return $this->belongsToMany(Batch::class);
}
}
and students
class Student extends Model
{
public $guarded = [];
public function batches()
{
return $this->belongsToMany(Batch::class)->withPivot(['batch_id']);
}
public function grades()
{
return $this->belongsToMany(Grade::class);
}
}
tables students . batches. grades. batch_student, batch_grade. and grade_student . dont solve the problem. if I select a grades student It shows all students even who are in previous batch in this grade. need a table like student_grade_batch. so 3 foreign keys.

Not able to create eloquent relationship with table which have custom primary key

When i'm trying to get user details from company Model i'm getting NULL value.
class User extends Model
{
protected $primaryKey = 'uid';
}
class Company extends Model
{
$table = 'company';
public function users(){
return $this->hasMany('App\User','user_id','uid');
}
}
class RepoController{
public function index(){
$user = Company::where('id',1)->with('user')->get();
/// Returning value but without Users
}
}`
users table should contain company_id and you should define id as company ID because company table doesn't use custom ID:
public function users()
{
return $this->hasMany('App\User', 'company_id', 'id');
}
Or just this:
public function users()
{
return $this->hasMany('App\User');
}
Also, you're trying to load user relationship, but it should be users(), so do this instead:
Company::where('id', 1)->with('users')->get();
I think your ids are in wrong position
try swapping them like
return $this->hasMany('App\User','uid','user_id');

Relationship: belongsTo this model or a different model

We have the following
Manager
[id]
Companies
[id]
[manager_id] not nullable
Stores
[id]
[company_id]
[manager_id] *nullable*
I am looking for a single Eloquent relationship for the manager of every store.
Any suggestions?
Building on your comment #Sanjay S
class Store extends Model {
public function manager() {
return $this->belongsTo('App\Manager');
}
public function getManager() {
if (is_null($this->manager)) {
return $this->company()->manager;
} else {
return $this->manager;
}
Then when you call $store->getManager() you will get the company manager if store manager_id is null
You question is not clear as your relationship in the stores table is like manager_id [nullable] and you are asking for a single Eloquent relationship for the manager of every store. But from my guesses your Eloquent models should be look like this
class Manager extends Model {
public function stores() {
return $this->hasMany(App\Store::class);
}
public function company() {
return $this->hasOne(App\Company::class);
}
}
Company class
class Company extends Model {
public function manager() {
return $this->belongsTo(App\Manager::class);
}
}
Store class
class Store extends Model {
public function manager() {
return $this->belongsTo(App\Manager::class);
}
}
Hope this solution works for you.

Is it possible to insert record through chain foreign key relationship in Laravel 5.2

I have three tables/models :user,employee and employee_disability.
employee has foreign key user_id.
employee_disability contain emp_id foreign key.
Is there a way to perform the following action:
$user->employee()->empdisability()->create(['name'=>$name,'percent'=>$percent]);
Any help is appreciated. Thank You in advance.
MODELS:
class user extends Authenticatable{
public function employees(){
return $this->hasMany('App\Models\employee','user_id');
}
}
class employee extends Model{
public function user(){
return $this->belongsTo('App\Models\user','user_id');
}
public function empdisability(){
return $this->hasMany('App\Models\emp_disability','emp_id');
}
}
class emp_disability extends Model{
public function employee(){
return $this->belongsTo('App\Models\employee','emp_id');
}
}
CONTROLLER
public function storeDisability(Request $request){
$user=Auth::user();
$name=$request->name; $percent=$request->percent;
$user->employee()->empdisability()->create(['name'=>$name,'percent'=>$percent]);
}
$user->employee() returns the query builder for the employee relation, but what you need is the instance.
This should work, notice the lack of parantheses on employee
$user->employee->empdisability()->create(['name'=>$name,'percent'=>$percent]);

Laravel Eloquent Relationship Through Another Table

I have the following database tables:
Seasons
id
number
Teams
id
name
Standings
id
season_id
team_id
The question is, how could I get all of the teams in a season through the standings table. At the moment I am getting all of the teams this way:
$teams = [];
$standings = $season->standings;
foreach($standings as $standing){
$teams[] = $standing->team;
}
Is there a way I could do this using Eloquent relationships? I have tried HasManyThrough with no success. These are what my models look like currently:
class Season extends Eloquent{
public function standings(){
return $this->hasMany('Standing');
}
}
class Standing extends Eloquent{
public function team(){
return $this->belongsTo('Team');
}
}
class Team extends Eloquent{
public function standings(){
return $this->belongsToMany('Standing');
}
}
Your relationships look a little off. Here is all the relationships you should need though only the belongsToMany ones are required for this specific scenario of finding all the teams in a season.
class Season extends Eloquent {
public function teams()
{
return $this->belongsToMany('Team', 'Standings');
}
public function standings()
{
return $this->hasMany('Standing');
}
}
class Team extends Eloquent {
public function seasons()
{
return $this->belongsToMany('Season', 'Standings');
}
public function standings()
{
return $this->hasMany('Standing');
}
}
class Standing extends Eloquent {
public function team()
{
return $this->belongsTo('Team');
}
public function season()
{
return $this->belongsTo('Season');
}
}
You would use the belongsToMany relationship rather than a hasManyThrough to query all the teams in a season. That would look something like...
Season::with('teams')->find($season_id);
foreach($season->teams as $team) {
echo $team->name;
}

Resources