或 Laravel 查询生成器中的查询

Use*_*r57 2 php mysql query-builder laravel

我试图找到不是免费产品并且产品状态处于活动状态的产品,即 1 但问题是它在以下查询中无法按我想要的方式工作。它为产品系列提供了非活动和免费的我想要的匹配项。如何通过修改以下查询来获得适当的输出?这$query是搜索关键字

$products = DB::table('products')                       
            ->where('products.name' , 'like', '%'.$query.'%')
            ->orWhere('products.tags','like','%'.$query.'%')               
            ->where('products.status','=',1)    
            ->where('products.price','!=',0)            
            ->groupBy('products.id')
            ->latest()
            ->paginate(3);
Run Code Online (Sandbox Code Playgroud)

eka*_*ans 5

you need to encapsulate your orWhere :

$products = DB::table('products')
        ->where(function($q) use ($query){    
            $q->where('products.name' , 'like', '%'.$query.'%')
            ->orWhere('products.tags','like','%'.$query.'%');
        })               
        ->where('products.status','=',1)    
        ->where('products.price','!=',0)            
        ->groupBy('products.id')
        ->latest()
        ->paginate(3);
Run Code Online (Sandbox Code Playgroud)

Which should be render something like

SELECT * FROM 'products' 
WHERE (
    products.name like '%query%' OR 
    products.tags like '%query%'
) AND 
products.status = 1 AND 
products.price <> 0
GROUP BY products.id
Run Code Online (Sandbox Code Playgroud)