Laravel 4.x,Eloquent 多条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24394815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:42:01  来源:igfitidea点击:

Laravel 4.x, Eloquent multiple conditions

mysqlarrayslaravelconditional-statementswhere

提问by RonZ

I've tried to this:

我试过这个:

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

This isn't working at all. When I'm doing this:

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

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

It just works fine. I've searched in the documentation of Laravel, and found nothing.

它工作正常。我在 Laravel 的文档中搜索过,一无所获。

Is there any option to using the wherefunction with an array in it ?

是否有任何选项可以将where函数与数组一起使用?

回答by Dave

You need to use where() individually. If you want to dynamically building the query you can do something like:

您需要单独使用 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();

回答by Jarek Tkaczyk

In fact we were all wrong ;)

事实上我们都错了;)

As of latest version of the framework you can do exactly what you wanted.

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

Check this commit and update Laravel if you need that feature.

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

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

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

回答by Brian Monteiro

Product::whereNested(function($query) use ($key, $product){
            $query->where('product_id', $product->id);
            $query->where('catalog_id', $key);
        })->get();

回答by Jake Wilson

Laravel's wheres use an andcondition by default:

Laravel 的默认where使用and条件:

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

is somewhat equivalent to:

有点等价于:

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

You simply chain the ->where()methods together. No need for an array.

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

If you want to use an orcondition:

如果要使用or条件:

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