【问题标题】:Query ignoring conditions because of orwhere - Laravel5由于 orwhere 查询忽略条件 - Laravel5
【发布时间】:2023-03-04 16:06:02
【问题描述】:

我有一个产品搜索,通过名称、描述和关键字进行搜索...

有 3 列包含这些项目,如下所示: 名称、描述和关键字

我的问题是这样的,当我搜索产品时,查询会返回一个包含多个产品的列表,但其中一些产品不应该列出,因为不符合所有要求....跟随查询:

我的行动:

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

执行查询时,返回的产品不符合“productsAvailable”标准,应该是 fornecedor.ativo = 1 和 produtos.ativo = 1 (true)

尽管在查询中是隐式的,但由于 orWhere 子句,它会被忽略。

我的疑问是如何不使用这个 orWhere 并让我的查询搜索产品名称、描述和关键词?

简而言之,如何在不忽略 productsAvailable 函数的条件下,通过列名、描述和关键字获取产品?

【问题讨论】:

    标签: mysql sql laravel laravel-5 eloquent


    【解决方案1】:

    代替:

    $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();
    

    你应该使用:

    $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();
    

    如您所见,条件被包装到额外的 where 以在查询中添加括号

    【讨论】:

    • 谢谢!我会再试一次午餐
    • 成功了!谢谢!我可以在哪里阅读有关此功能的任何文章?我想了解更多。
    • @Dayglor 最好的起点是 Laravel 文档。其中条件分组是专门针对here.
    • 太棒了!谢谢@patricus
    猜你喜欢
    • 1970-01-01
    • 2015-02-26
    • 2023-02-21
    • 1970-01-01
    • 1970-01-01
    • 2015-05-09
    • 2016-12-18
    • 2015-02-22
    • 2016-11-21
    相关资源
    最近更新 更多