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

时间:2019-05-09 11:15:28

标签: 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();
    }
}

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

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(

        );
    }


}

导致以下错误:

  

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

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

1 个答案:

答案 0 :(得分:3)

这是使用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']);;