【问题标题】:How to add custom methods to eloquent model in a way we can chain them?如何以我们可以链接它们的方式将自定义方法添加到 eloquent 模型?
【发布时间】:2019-09-27 05:11:56
【问题描述】:

我想要的是向 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(

        );
    }


}

导致以下错误:

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

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

【问题讨论】:

标签: laravel eloquent laravel-query-builder


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-25
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多