phpmyadmin 我在laravel模型中用我的自定义newQuery函数覆盖newQuery,在特定函数中,我想跳过自定义newQuery的条件

sh7euo9m  于 2023-03-18  发布在  PHP
关注(0)|答案(1)|浏览(120)

模型中自定义新查询函数:我使用了protected $和=['newQuery'];模型中

public function newQuery(){
        $query = parent::newQuery();
        $query->where('slug','!=', "example");
        return $query;
    }

我想在特定函数中禁用这个自定义NewQuery函数。我使用它时没有使用(newQuery),但它不起作用,

beq87vna

beq87vna1#

您不应该覆盖newQuery()。如果您希望有一个条件与您(对该模型)进行的每个查询一起运行,则应该创建一个单独的查询范围

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class YourModel extends Model
{
    protected static function booted(): void
    {
        static::addGlobalScope('filter-examples', function (Builder $builder) {
            $builder->where('slug', '<>', 'example');
        });
    }
}

这样,您就可以定义多个全局范围。如果要在没有该范围的情况下运行查询,可以使用withoutGlobalScope(scope)方法

$results = YourModel::withoutGlobalScope('filter-examples')->get();

更多信息

相关问题