Mohd Domais
Mohd Domais

Reputation: 43

How to retrieve multiple relations with multiple tables in laravel eloquent

I'm using Laravel 5.8 to build a babysitting site. I have 4 tables with different relationships as below:

please see this image

The relationships are:

Babysitter->hasMany(session)
Sessions->hasOne(Review)
Sessions->hasOne(Kids)
Sessions->hasOne(Babysitter)
Sessions->hasOne(Parent)

I want to achieve 2 things:

First one

I want to show this result when listing all babysitters. I'm showing this information for each babysitter:

plsease see this image

See here what I couldn't achieve

plsease see this image

This is my code

Sitters::where('Status', 'active')->where('Verified', 1)->get();

Second one

Also, I've tried to show kids name with parent review as shown here:

plsease see this image

This is what i'm using

Sessions::select('Reviews.*', 'Sessions.Parent_id')->join('Reviews', 'Reviews.Session_id', '=', 'Sessions.id')->with('owner')->where('Trainer_id', session('user')->Id)->where('Status', '=', 'complete')->with('owner')->orderBy('Sessions.id', 'DESC')->get();

Here is Session.php Model

public function owner(){
    return $this->belongsTo('App\Models\Parents', 'Parent_id');
}

Upvotes: 0

Views: 229

Answers (2)

Mohd Domais
Mohd Domais

Reputation: 43

After a few days of searching & testing, this is what worked for me:

Inside (Sitters) Model, put this relation

public function sessions()
{
    return $this->hasMany(Sessions::class, 'sitter_id')
        ->withCount('reviews')
        ->withCount(['reviews as review_avg' => function($query){
            $query->select(DB::raw('AVG(Rating)'));
        }]);
}

Also, inside (Sessions) Model, put this relation

public function reviews()
{
    return $this->hasOne(Reviews::class, 'Session_id');
}

Now you query like this

return $sitters = Sitters::with('sessions')->get();

I hope this can help someone :)

Upvotes: 0

N69S
N69S

Reputation: 17216

As discussed change the relations:

Babysitter->hasMany(sesstion)
Sessions->hasOne(Review)
Sessions->belongsTo(Kids)
Sessions->belongsTo(Babysitter)
Sessions->belongsTo(Parent)

First one

in Babysitter.php declare the following attributes

class Babysitter extends Model
{
    public function reviews()
    {
        $this->hasManyThrough(Review::class, Session::class);
    }

    public function getAverageReviewAttribute()
    {
        return $this->reviews()->avg('Rating');
    }
}

Then you just need to call it on the model instance.

$babysitter = Babysitter::first();
return $babysitter->average_review;

Second one

Just use the relation

$babysitter = BabySitter::with(['sessions' => public function ($session) {
        $session->with(['review','parent','kids']);
    })->where('trainer_id', '=', session('user')->Id) //did not understand this condition
    ->first();

This assumes you have parent, kids and review relation declared on Session::class. (change the names if needed)

Upvotes: 1

Related Questions