如何以我们可以链接它们的方式将自定义方法添加到 eloquent 模型?

How to add custom methods to eloquent model in a way we can chain them?

我想要的是向 eloquent 模型添加方法,以便我可以链接它们,例如:

class MovieResolver
{
    public function getMoviesFeaturingToday(array $args)
    {
        // Movie is an Eloquent model

        $movie = (new Movie())
            ->getMoviesFeaturingTodayOnTheater($args['movieTheaterId'])
            ->getBySessionCategory($args['sessioncategory']);

        // And keep doing some operations if necessary, like the code below.
        // I cannot call the get() method unless I finish my operations.

        return $movie->whereDate('debut', '<=', Carbon::today())
            ->orderBy('debut', 'desc')
            ->get();
    }
}

但是将这些方法添加到模型中:

class Movie extends Model
{
    public function getMoviesFeaturingTodayOnTheater($theaterId)
    {
        return $this->whereHas(
            'sessions.entries.movieTheaterRoom',
            function ($query) use ($theaterId) {
                $query->where('movie_theater_id', $theaterId);
            }
        );
    }

    public function getBySessionCategory($sessionCategory)
    {
        return $this->whereHas(

        );
    }


}

导致以下错误:

Call to undefined method Illuminate\Database\Eloquent\Builder::getMoviesFeaturingTodayOnTheater()

但是为什么呢?我做错了什么?

这是使用 Query Scopes 完成的。所以在你的模型中试试这个:

public function scopeMoviesFeaturingTodayOnTheater($query, $theaterId)
{
    return $query->whereHas(
           'sessions.entries.movieTheaterRoom',
            function ($query) use ($theaterId) {
                $query->where('movie_theater_id', $theaterId);
            }
        );
}

public function scopeBySessionCategory($query, $sessionCategory)
{
     return $query->whereHas(
        // ...
     );
}

然后使用它:

Movie::moviesFeaturingTodayOnTheater($args['movieTheaterId'])
    ->bySessionCategory($args['sessioncategory']);;