Laravel范围和搜索结果

时间:2017-11-17 00:03:09

标签: php laravel laravel-blade

我正在使用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仍会在搜索结果中弹出,问题仍然存在。

  

同样适用于产品列表,仍然在网站上显示。

我该如何解决?

2 个答案:

答案 0 :(得分:0)

尝试:

template<typename E2> VecSum<int, E2>{ /*stuff goes here*/ }
template<typename E1> VecSum<E1, int>{ /*stuff goes here*/ }
template<typename E2> VecSum<float, E2>{ /*stuff goes here*/ }
template<typename E1> VecSum<E1, float>{ /*stuff goes here*/ }
template<typename E2> VecSum<double, E2>{ /*stuff goes here*/ }
template<typename E1> VecSum<E1, double>{ /*stuff goes here*/ }

答案 1 :(得分:0)

您的问题是您正在添加本地范围而非全局范围。

您仍然可以使用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