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
Laravel 4.x, Eloquent multiple conditions
提问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 where
function 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 where
s use an and
condition 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 or
condition:
如果要使用or
条件:
$products = Product::where('this','=','that')->orWhere('something','=','hello')->get();