如何使用Laravel雄辩创建多个where子句查询? [英] How to create multiple where clause query using Laravel Eloquent?

查看:128
本文介绍了如何使用Laravel雄辩创建多个where子句查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Laravel Enloquent查询构建器,并且我在多个东西上查询我想要一个 WHERE 子句。它的作品,但它不优雅。



示例:

  $ results = User :: 
其中('this','=',1)
- >其中('that','=',1)
- >其中('this_too','=' )
- > where('that_too','=',1)
- > where('this_as_well','=',1)
- > where('that_as_well ','=',1)
- > where('this_one_too','=',1)
- > where('that_one_too','=',1)
- > where('this_one_as_well','=',1)
- > where('that_one_as_well','=',1)
- > get();

有没有更好的方法来做,还是应该坚持这种方法?

解决方案

在Laravel 5.3 中,您可以使用更多细粒度的数组作为数组传递:

  $ query-> where([
['column_1','=','value_1'],
['column_2' ''','value_2'],
[COLUMN,OPERATOR,VALUE],
...
])

个人我没有找到这个用例,只是多个其中调用,但事实是你可以使用它。



自2014年6月以来,您可以将数组传递到其中 / p>

只要你想要所有的 wheres 使用运营商,您可以这样分组:

  $ matchThese = ['field'=> 'value','another_field'=> 'another_value',...] 

//如果您需要另一组作为替代方案:
$ orThose = ['yet_another_field'=> 'yet_another_value',...]

然后:

 code> $ results = User :: where($ matchThese) - > get(); 

//与另一个组
$ results = User :: where($ matchThese)
- > orWhere($ orThose)
- > get() ;

以上将导致这样的查询:

  SELECT * FROM users 
WHERE(field = value AND another_field = another_value AND ...)
OR(yet_another_field = yet_another_value AND ...)


I'm using the Laravel Eloquent query builder and I have query where I want a WHERE clause on multiple things. It works, but it is not elegant.

Example:

$results = User::
      where('this', '=', 1)
    ->where('that', '=', 1)
    ->where('this_too', '=', 1)
    ->where('that_too', '=', 1)
    ->where('this_as_well', '=', 1)
    ->where('that_as_well', '=', 1)
    ->where('this_one_too', '=', 1)
    ->where('that_one_too', '=', 1)
    ->where('this_one_as_well', '=', 1)
    ->where('that_one_as_well', '=', 1)
    ->get();

Is there a better way to do this, or should I stick with this method?

解决方案

In Laravel 5.3 you can use more granular wheres passed as array:

$query->where([
    ['column_1', '=', 'value_1'],
    ['column_2', '<>', 'value_2'],
    [COLUMN, OPERATOR, VALUE],
    ...
])

Personally I haven't found use-case for this over just multiple where calls, but fact is you can use it.

Since June 2014 you can pass an array to where

As long as you want all the wheres use and operator, you can group them this way:

$matchThese = ['field' => 'value', 'another_field' => 'another_value', ...];

// if you need another group of wheres as an alternative:
$orThose = ['yet_another_field' => 'yet_another_value', ...];

Then:

$results = User::where($matchThese)->get();

// with another group
$results = User::where($matchThese)
    ->orWhere($orThose)
    ->get();

The above will result in such query:

SELECT * FROM users
  WHERE (field = value AND another_field = another_value AND ...)
  OR (yet_another_field = yet_another_value AND ...)

这篇关于如何使用Laravel雄辩创建多个where子句查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆