mysql - laravel 条件数据库查询

标签 mysql sql laravel

如果名称不为空,我将如何进行有条件的 laravel 查询,考虑到我尝试过但没有奏效的内容,我会尝试获取具有特定名称的产品

这个不行!!

public function getProducts($page = null, $match=null, $price = null) {
    if ($page != null)
        DB::getPaginator()->setCurrentPage($page);
        $products = Product::join('product_specs', 'products.productid', '=', 'product_specs.product_id')
                ->join('feeds_categories', 'product_specs.category', '=', 'feeds_categories.id')
                ->where('feeds_categories.name', '=', 'Notebooks')
                ->where('products.status', '=', 1)
                ->where('products.price', '>', 250)
                ->orderBy('products.price', 'ASC')
                ->paginate(10);
   if($match !='') $products->where('productname','LIKE','%'.$match.'%');    
   return $products;
}

最佳答案

您没有将查询构建器重新分配回 $products 变量。试试这个:

if($match !='') $products = $products->where('productname','LIKE','%'.$match.'%');

事实上,您还需要将其移动到 ->paginate(10) 之前。

public function getProducts($page = null, $match=null, $price = null) {

        ...
        ->where('products.price', '>', 250); // Notice I added a semi-colon here.

    if($match !='') $products = $products->where('productname','LIKE','%'.$match.'%'); 

    $products = $products->orderBy('products.price', 'ASC')
        ->paginate(10);

    return $products;
}

关于mysql - laravel 条件数据库查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24580782/

相关文章:

mysql - MySQL 查询中 '".$string ."' 和 '$string"之间有什么不同

MySQL 排列现有表列

php - mysql查询和while循环创建一个特殊的字符串

java - JDBC:在 MySQL 上运行 `insert` 查询时出现 OutOfMemoryError

laravel - 如何在共享主机上运行队列工作程序

php - spatie/pdf-to-image 1.8.2 需要 ext-imagick composer 安装时出错

mysql - SQL 查询返回几十年来的最大值

MySql 查询在 2 个表之间执行连接

sql - PostgreSQL 分组错误

laravel - 模型关系在这种情况下如何运作?