Junaid Abbas
Junaid Abbas

Reputation: 11

hasMany and belongsTo in laravel

I have a Student in the users table, Parent is in the same table, and that Parent is the parent of that Student.

The Student has a Schedule in the schedules table.

How I can write hasMany and belongsTo to get the proper relation like in following custom query which works fine:

$schedules = DB::table('users')
  ->join('schedules', 'users.id', '=', 'schedules.studentID')
  ->select('users.*', 'schedules.*', 'users.fname as fname', 'users.lname as lname')
  ->where('users.parent_id',$request->id)
  ->where('schedules.status','1')
  ->where('schedules.status_dead','0')
  ->whereIn('schedules.std_status',[1, 2])
  ->get();

As shown in the image below:

Upvotes: 1

Views: 68

Answers (1)

Hasan Teoman Tıngır
Hasan Teoman Tıngır

Reputation: 2901

Before the relationship lets create parent scope and find student more elegant way

User Model

public function scopeByParent($query,$parentId){
    return $query->where("parent_id",$parentId);
}

Above scope provide us to get user or users by parent id.

Then create relationships.

User Model

public function schedules(){
   return $this->hasMany("App\Schedule","studentID","id");
}

Schedule Model

public function users(){
   return $this->belongsTo("App\User","id","studentID");
}

Then lets create our query using above scope and relation.

User::with(["schedules" => function ($query) {
    $query->whereStatusAndStatusDead(1, 0)
         ->whereIn('std_status', [1, 2]);
    }])
    ->byParent($request->id)
    ->get();

Upvotes: 1

Related Questions