L
L
Li2021-04-11 19:08:29
Laravel
Li, 2021-04-11 19:08:29

How to display the last episode in the series list?

Guys please help me figure it out. I have a table of serials and episodes. Communication one to many. On the main page I display a list of series in which for each series it is necessary to display the name of the last added series.

Tried like this:

Serial Model
    public function series()
    {
        return $this->hasMany(Series::class, 'serial_id', 'id');
    }

    public function getLastSeriesAttribute()
    {
        return $this->series->first();
    }


One series is displayed, however, for each film, models of all the series of the film are loaded, and I have 50-100 of them for each film. Is there a method for solving this problem without an additional request for each movie? Thank you for your help

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey delphinpro, 2021-04-11
@delphinpro

return $this->series()->orderByDesc('номер серии')->first()

->series()- use a method, not a property, for additional conditions.

J
jazzus, 2021-04-11
@jazzus

In the model

public function lastEpisode()
{
     // или с другой сортировкой
    return $this->hasOne(Series::class)->latest();   
}

in controller
Serial::with('lastEpisod')
    ->get();

in the template, refer to lastEpisod for each series.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question