【问题标题】:Use Where in QueryBuilder - Laravel在查询生成器中使用 Where - Laravel
【发布时间】:2019-05-06 13:48:56
【问题描述】:

我有一张表 Products(id,category_id,name);

我想得到这样的查询结果:

SELECT * FROM Products WHERE category_id=$category_id OR $category_id=0;

当我为 $category_id 分配 0 值 => 上面的查询将返回所有记录。

如何在 Laravel 中编写该查询?

我试过这个:

Products::where(function($query) use ($category_id){
         $query->where("category_id",$category_id)
        ->orWhere($category_id,0)
})->get();

但是,错误:

看起来像:

SELECT
    *
FROM
    `products` 
WHERE
    ( `product_category_id` = 0 OR `0` = 0 )

并且打印错误:Column not found: 1054 Unknown column '0' in 'where clause'

如何解决:'0' = 00 = 0

谢谢!

【问题讨论】:

  • 请确保将您的模型命名为Product,而不是Products。模型是单一的。

标签: laravel eloquent laravel-query-builder


【解决方案1】:

使用when():

$products = Product::when($categoryId, function ($query, $categoryId) {
    $query->whereCategoryId($categoryId);
})->get();

只有条件为真时,该方法才会调用该函数。您可以使用简单的if 语句实现同样的目的:

$products = Product::query();

if ($categoryId) {
    $products->whereCategoryId($categoryId);
}

$products = $products->get();

使用when() 的好处是不会破坏链条,因此您可以在一个表达式中使用条件查询更改。例如,如果您只想return 它会很有用。

【讨论】:

  • 不行!当通过 $category_id=0。您的查询没有返回任何内容!它看起来像:SELECT * FROM 'products' WHERE category_id IN (0,0);
  • 如果你通过category_id = 0,你期望得到什么?
  • 如果我有一些字段类别值为[1,2,3,4...]的记录。那么当通过$category_id=0时,会返回products表中的所有记录
  • 这改变了一切。请查看我的更新答案。
  • 以前一样。它看起来像这样:SELECT * FROM 'products' WHERE category_id=0。当我通过$category_id=0。我想要这个:SELECT * FROM Products WHERE category_id=$category_id OR $category_id=0;。因此,当我传递$category_id=1 时,查询将返回category=1 的所有记录,当我传递$category_id=0 时,它返回products 表中的所有记录。
【解决方案2】:

使用它

Products::where(function($query) use ($category_id){
         $query->where("category_id",$category_id)
        ->orWhere("category_id",0);
})->get();

【讨论】:

  • 在我的数据中,没有任何记录有category_id=0。我希望通过$category_id=0 我的查询将返回所有记录。你的方式,我用过(见我的帖子)
【解决方案3】:

您的代码有什么问题:

->orWhere($category_id,0)

您将列部分设置为变量。

试试这个代码:

Products::where(function($query) use ($category_id){
         return $query->where("category_id", $category_id)
        ->orWhere("category_id", 0);
})->get();

【讨论】:

    【解决方案4】:
    $product = new Products;
    if ($category_id != 0) {
        $product = $product->where("category_id", $category_id);
    }
    $products = $product->get();
    

    【讨论】:

    • 为您的答案提供一些背景知识可能会有所帮助,这样将来的访问者会更清楚。
    猜你喜欢
    • 2018-01-03
    • 2018-12-26
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 2016-08-16
    • 2015-12-14
    • 1970-01-01
    • 2015-07-25
    相关资源
    最近更新 更多