Laravel 范围和搜索结果

Laravel Scope and Search results

我正在与 laravel 5.5 合作,我在 Product.php 模型中为我的产品设定了范围:

public function scopeApproved($query)
{
    return $query->where('publish', 1);
}

摘自 laravel 网站。

然后我有下面这段代码来显示我的搜索结果。

public function search()
{
    $search = request('search');
    $searchType = request('searchType');

    if (strcmp($searchType, "posts") == 0) {
        $posts = Post::where('title', 'like', "%{$search}%")
            ->orWhere('description', 'like', "%{$search}%")
            ->get();
    } elseif (strcmp($searchType, "products") == 0) {
        $products = Product::where('title', 'like', "%{$search}%")
            ->orWhere('description', 'like', "%{$search}%")
            ->get();
    }

    return view('frontend.search', compact('posts', 'products'));
}

问题是即使我的产品 publish 列设置为 0 仍然会在搜索结果中弹出。

same goes for products list, still shows in website.

我该如何解决?

尝试:

public function search()
{
    $search = request('search');
    $searchType = request('searchType');

    if (strcmp($searchType, "posts") == 0) {
        $posts = Post::approved()->where('title', 'like', "%{$search}%")
            ->orWhere('description', 'like', "%{$search}%")
            ->get();
    } elseif (strcmp($searchType, "products") == 0) {
        $products = Product::approved()->where('title', 'like', "%{$search}%")
            ->orWhere('description', 'like', "%{$search}%")
            ->get();
    }

    return view('frontend.search', compact('posts', 'products'));
}

您的问题是您添加的是局部范围而不是全局范围。

您仍然可以使用本地范围执行 Product::approved()

但是对于全局范围,您需要在 Product.php 中创建启动方法,如下所示:

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

    static::addGlobalScope('publish', function (Builder $builder) {
        $builder->where('publish', 1);
    });
}

如果你想要没有全球范围的产品Product::withoutGlobalScopes()->get();

应该可以了。

也看看https://laravel.com/docs/5.5/eloquent#global-scopes