Reputation: 155
I have a product search that makes searching by name , description and also keywords ...
There are 3 columns that contain these items , as follows: Name, description and keywords
My problem is this , when I do a search for products query returns me a list with several products , but some of them should not be listed for not meeting all the requirements .... follows the query :
My action :
public function search( $data )
{
$products = $this->queryProductsAvailable()
->where('produtos.nome', 'like', '%'.$data.'%')
->orWhere('produtos.descricao', 'like', '%'.$data.'%')
->orWhere('produtos.palavras_chave', 'like', '%'.$data.'%')
->limit( $this->_limitProducts )
->orderBy( 'fornecedores.plano_id', 'DESC' )
->get();
$this->savePrint( $products );
// $categories = $this->setCategories();
return view('Catalogo.search', [
'products' => $products,
'searchTerm' => $data
]
);
}
private function queryProductsAvailable()
{
return Products::join('fornecedores', 'fornecedores.id', '=' ,'produtos.fornecedor_id')
->where( 'fornecedores.ativo', 1)
->where( 'produtos.moderacao', "P" )
->where( 'produtos.ativo' , true )
->where( 'produtos.preco_min', '>', 0 )
->select( 'produtos.*');
// ->limit( $this->_limitProducts );
}
When the query is executed are returned products that are not in the standard of "productsAvailable" which should be fornecedor.ativo = 1 and produtos.ativo = 1 (true)
Despite being implicit in the query , it ignores because of the orWhere clauses .
My doubt is how to not use this orWhere and make my query search the product name , description and also the key words ?
In short , how do I get the products by column name , description and keywords , without ignoring the terms of the function productsAvailable ?
Upvotes: 1
Views: 927
Reputation: 111889
Instead of:
$products = $this->queryProductsAvailable()
->where('produtos.nome', 'like', '%'.$data.'%')
->orWhere('produtos.descricao', 'like', '%'.$data.'%')
->orWhere('produtos.palavras_chave', 'like', '%'.$data.'%')
->limit( $this->_limitProducts )
->orderBy( 'fornecedores.plano_id', 'DESC' )
->get();
you should use:
$products = $this->queryProductsAvailable()
->where(function($q) use ($data) {
$q->where('produtos.nome', 'like', '%'.$data.'%')
->orWhere('produtos.descricao', 'like', '%'.$data.'%')
->orWhere('produtos.palavras_chave', 'like', '%'.$data.'%')
})->limit( $this->_limitProducts )
->orderBy( 'fornecedores.plano_id', 'DESC' )
->get();
As you see conditions were wrapped into additional where to add brackets into query
Upvotes: 4