iizno
iizno

Reputation: 849

How to get the last (per date) joined row for each result with Laravel Eloquent

Here is what I want to achieve :

I have a Formation model which have FormationSession model. I need all formations with, for each, the last session in database.

Here is what I got so far :

$formations = Formation::query()
    ->with('location')
    ->with('jobs')
    ->with('employee')
    ->with('intervenant.company')
    ->with(['formation_sessions' => function($query) {
        $query->limit(1)->orderBy('start_at', 'desc');
    }])
    ->whereNotNull('update_frequency')
    ->get();

I'm pretty stuck here, how can I achieve this ?

Upvotes: 1

Views: 40

Answers (1)

Binit Ghetiya
Binit Ghetiya

Reputation: 1979

You can create another relationship something like

public function formation_sessions_last(){
    return $this->belongsToMany('App\FormationSession','formation_id')
                ->orderBy('start_at')->limit(1);
}
#App\FormationSession  => FormationSession Modal
#formation_id          => foreign_key

Then you can call query

->with('formation_sessions_last')

Hope this will help.

Upvotes: 1

Related Questions