如何以可以链接的方式将自定义方法添加到雄辩模型中?

e20*_*200 1 laravel eloquent laravel-query-builder

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

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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(

        );
    }


}
Run Code Online (Sandbox Code Playgroud)

结果出现以下错误:

调用未定义的方法 Illuminate\Database\Eloquent\Builder::getMoviesFeaturingTodayOnTheater()

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

nak*_*kov 6

这是使用查询范围来完成的。因此,请在您的模型中尝试以下操作:

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(
        // ...
     );
}
Run Code Online (Sandbox Code Playgroud)

然后要使用它,您需要执行以下操作:

Movie::moviesFeaturingTodayOnTheater($args['movieTheaterId'])
    ->bySessionCategory($args['sessioncategory']);;
Run Code Online (Sandbox Code Playgroud)