简体   繁体   English

Laravel范围和搜索结果

[英]Laravel Scope and Search results

I'm working with laravel 5.5 and I made scope for my products in Product.php model: 我正在使用laravel 5.5,并在Product.php模型中确定了产品范围:

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

Taken from laravel website. 取自laravel网站。

Then I have this code below to show my search results. 然后,我将在下面的代码中显示我的搜索结果。

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'));
}

The problem with that is even if my product publish column is set to 0 still will pop in search results. 即使我的产品publish列设置为0仍然会出现在搜索结果中。

same goes for products list, still shows in website. 产品清单也是如此,仍显示在网站上。

How can I fix that? 我该如何解决?

Try: 尝试:

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'));
}

Your issue is you are adding local scope rather the global scope. 您的问题是要添加本地范围而不是全局范围。

You can still use you local scope doing Product::approved() 您仍然可以通过Product::approved()使用本地范围

But for global scope you need to create boot method in your Product.php like so: 但是对于全局范围,您需要在Product.php创建启动方法,如下所示:

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

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

if you want product without global scope Product::withoutGlobalScopes()->get(); 如果您想要的产品没有全局范围Product::withoutGlobalScopes()->get();

That should do it. 那应该做。

Also have a look at https://laravel.com/docs/5.5/eloquent#global-scopes 也可以看看https://laravel.com/docs/5.5/eloquent#global-scopes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM