Laravel Eloquent 如何覆盖基本查询?

Laravel Eloquent how to override the base query?

我有 2 个模型共用一个 table。

Table name: books, 我通过名为 type

的属性将普通书籍和小说分开

图书型号

class Book extends \Illuminate\Database\Eloquent\Model
{
    protected $table = 'books';
}

小说型号

class Novel extends Book
{
    protected $table = 'books';

    // Is such a method available?
    protected function someMethodToOverride()
    {
        $this->where('type', 'novel');
    }
}

我这里要实现的是

$results = Novel::where('title', 'LIKE', '%' . $title . '%')->get();

从这个查询中,我希望它预先设置条件

where('type', 'novel')

有没有我可以覆盖的函数来实现这个?

在模型中您可以使用范围:

public function scopeOfType($query, $type)
{
    return $query->where('type', $type);
}

并在调用作用域时传递参数:

 Model::ofType('novel')
        ->where('title', 'LIKE', '%' . $title . '%')
        ->get();

参考linkLaravel Scope

使用匿名全局范围并在 Novel 模型中添加此引导方法

protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('type', function (\Illuminate\Database\Eloquent\Builder $builder) {
            $builder->where('type', 'novel');
        });
    }

现在它会自动添加查询

$results = Novel::where('title', 'LIKE', '%' . $title . '%')->get();

now If you would like to remove a global scope for a given query, you may use the withoutGlobalScope method.

Novel::withoutGlobalScope('type')->get();

有关详细信息,请阅读此 article