【问题标题】:Laravel 4.x, Eloquent multiple conditionsLaravel 4.x,雄辩的多重条件
【发布时间】:2014-08-15 04:46:04
【问题描述】:

我已经试过了:

Product::where(['product_id' => $product->id, 'catalog_id' => $key])->first();

这根本行不通。当我这样做时:

Product:where('product_id', $product->id)->where('catalog_id', $key)->first();

它工作得很好。我在 Laravel 的文档中搜索过, 什么也没找到。

有没有使用 where 函数和数组的选项?

【问题讨论】:

  • 要么使用循环,要么扩展“QueryBuilder”并自己添加功能。
  • 更新:在最新版本的 Laravel 中是可能的,就像我的回答一样。

标签: mysql arrays laravel conditional-statements where


【解决方案1】:
Product::whereNested(function($query) use ($key, $product){
            $query->where('product_id', $product->id);
            $query->where('catalog_id', $key);
        })->get();

【讨论】:

    【解决方案2】:

    事实上我们都错了;)

    在最新版本的框架中,您可以完全按照自己的意愿行事。

    如果您需要该功能,请检查此提交并更新 Laravel。

    https://github.com/laravel/framework/commit/87b267a232983abdac7c23c2dc6b1b270dd24b8a

    【讨论】:

    • 4 天前,至少从 4.1 开始就应该存在。 +1 用于引用新内容并更新此问题。
    【解决方案3】:

    Laravel 的 wheres 默认使用 and 条件:

    $products = Product::where('this','=','that')->where('something','=','hello')->get();
    

    有点等价于:

    SELECT * FROM products WHERE this = 'that' AND something = 'hello';
    

    您只需将->where() 方法链接在一起。不需要数组。

    如果你想使用or 条件:

    $products = Product::where('this','=','that')->orWhere('something','=','hello')->get();
    

    【讨论】:

      【解决方案4】:

      您需要单独使用 where()。如果您想动态构建查询,您可以执行以下操作:

      $wheres = array('product_id' => $product->id, 'catalog_id' => $key);
      
      $q = new Product;
      
      foreach ( $wheres as $k => $v ) {
          $q = $q->where($k, $v); 
      }
      
      $products = $q->first();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-18
        • 2018-12-09
        • 2015-08-08
        • 2014-07-01
        • 2013-09-09
        • 2015-06-01
        • 1970-01-01
        相关资源
        最近更新 更多