如何使用Laravel Eloquent创建多个Where子句查询?

时间:2013-10-11 18:56:45

标签: php laravel eloquent laravel-query-builder

我正在使用Laravel Eloquent查询构建器,我有一个查询,我希望在多个条件下有WHERE子句。它有效,但它并不优雅。

示例:

$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();

有更好的方法可以做到这一点,还是应该坚持使用这种方法?

27 个答案:

答案 0 :(得分:460)

在Laravel 5.3 中,您可以使用更多粒度的数据传递:

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

就个人而言,我还没有找到多个where来电的用例,但事实是你可以使用它。

自2014年6月起,您可以将数组传递给where

只要您想要所有wheres使用and运算符,您就可以这样对它们进行分组:

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

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

然后:

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

// with another group
$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 ...)

答案 1 :(得分:76)

查询范围可以帮助您提高代码的可读性。

http://laravel.com/docs/eloquent#query-scopes

使用一些示例更新此答案:

在您的模型中,创建这样的范围方法:

public function scopeActive($query)
{
    return $query->where('active', '=', 1);
}

public function scopeThat($query)
{
    return $query->where('that', '=', 1);
}

然后,您可以在构建查询时调用此范围:

$users = User::active()->that()->get();

答案 2 :(得分:60)

您可以在匿名函数中使用子查询,如下所示:

 $results = User::where('this', '=', 1)
            ->where('that', '=', 1)
            ->where(function($query) {
                /** @var $query Illuminate\Database\Query\Builder  */
                return $query->where('this_too', 'LIKE', '%fake%')
                    ->orWhere('that_too', '=', 1);
            })
            ->get();

答案 3 :(得分:29)

在这种情况下,您可以使用以下内容:

<div id="intro_page" class="unseen">
	<div id="intro_page_content">
		<p id="intro_main_text" > Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p>
			
		<figure class="intro_pic1">
		<img src="http://sample.com/images/freeproductsamples.jpg" alt="Sample" height="250" />
		<figcaption>Sample Image 2015</figcaption>
		</figure>
	</div>
</div>

它应该为您提供如下查询:

User::where('this', '=', 1)
    ->whereNotNull('created_at')
    ->whereNotNull('updated_at')
    ->where(function($query){
        return $query
        ->whereNull('alias')
        ->orWhere('alias', '=', 'admin');
    });

答案 4 :(得分:19)

使用数组的条件:

$users = User::where([
       'column1' => value1,
       'column2' => value2,
       'column3' => value3
])->get();

会产生类似下面的查询:

SELECT * FROM TABLE WHERE column1=value1 and column2=value2 and column3=value3

使用反义词功能的条件:

$users = User::where('column1', '=', value1)
               ->where(function($query) use ($variable1,$variable2){
                    $query->where('column2','=',$variable1)
                   ->orWhere('column3','=',$variable2);
               })
              ->where(function($query2) use ($variable1,$variable2){
                    $query2->where('column4','=',$variable1)
                   ->where('column5','=',$variable2);
              })->get();

会产生类似下面的查询:

SELECT * FROM TABLE WHERE column1=value1 and (column2=value2 or column3=value3) and (column4=value4 and column5=value5)

答案 5 :(得分:9)

多个where子句

    $query=DB::table('users')
        ->whereRaw("users.id BETWEEN 1003 AND 1004")
        ->whereNotIn('users.id', [1005,1006,1007])
        ->whereIn('users.id',  [1008,1009,1010]);
    $query->where(function($query2) use ($value)
    {
        $query2->where('user_type', 2)
            ->orWhere('value', $value);
    });

   if ($user == 'admin'){
        $query->where('users.user_name', $user);
    }

最终获得结果

    $result = $query->get();

答案 6 :(得分:8)

whereColumn方法可以传递多个条件的数组。这些条件将使用and运算符加入。

示例:

$users = DB::table('users')
            ->whereColumn([
                ['first_name', '=', 'last_name'],
                ['updated_at', '>', 'created_at']
            ])->get();

$users = User::whereColumn([
                ['first_name', '=', 'last_name'],
                ['updated_at', '>', 'created_at']
            ])->get();

有关详细信息,请查看文档的此部分 https://laravel.com/docs/5.4/queries#where-clauses

答案 7 :(得分:5)

$projects = DB::table('projects')->where([['title','like','%'.$input.'%'],
    ['status','<>','Pending'],
    ['status','<>','Not Available']])
->orwhere([['owner', 'like', '%'.$input.'%'],
    ['status','<>','Pending'],
    ['status','<>','Not Available']])->get();

答案 8 :(得分:5)

def start_time():
    while True:
        try:
            starting = int(input("Please enter a starting hour(HH): "))
            if starting < 0:
                print("There are no negative hours!")
            elif starting > 24:
                print("There are only 24 hours in a day!")
            else:
                break
        except ValueError:
            print("Please enter in a correct format (HH)")
    return starting
def end_time():
    while True:
        try:
            ending = int(input("Please enter an ending hour (HH): "))
            if ending < starting:
                print("You can only plan a day!")
            elif ending < 0:
                print("There are only 24 hours in a day!")
            elif ending > 24:
                print("There are only 24 hours in a day!")
            else:
                break
        except ValueError:
            print("Please enter in a correct format (HH)")
    return ending

#obtain starting and ending time
start_time()
end_time()

#confirm starting and ending time

OR

Model::where('column_1','=','value_1')->where('column_2 ','=','value_2')->get();

OR

// If you are looking for equal value then no need to add =
Model::where('column_1','value_1')->where('column_2','value_2')->get();

答案 9 :(得分:5)

请务必将任何其他过滤器应用于子查询,否则可能会收集所有记录。

$query = Activity::whereNotNull('id');
$count = 0;
foreach ($this->Reporter()->get() as $service) {
        $condition = ($count == 0) ? "where" : "orWhere";
        $query->$condition(function ($query) use ($service) {
            $query->where('branch_id', '=', $service->branch_id)
                  ->where('activity_type_id', '=', $service->activity_type_id)
                  ->whereBetween('activity_date_time', [$this->start_date, $this->end_date]);
        });
    $count++;
}
return $query->get();

答案 10 :(得分:3)

您可以在 Laravel 5.3

中使用eloquent

所有结果

UserModel::where('id_user', $id_user)
                ->where('estado', 1)
                ->get();

部分结果

UserModel::where('id_user', $id_user)
                    ->where('estado', 1)
                    ->pluck('id_rol');

答案 11 :(得分:2)

使用whereIn条件并传递数组

$array = [1008,1009,1010];

User::whereIn('users.id', $array)->get();

答案 12 :(得分:2)

您可以通过多种方式使用,

$results = User::where([
    ['column_name1', '=', $value1],
    ['column_name2', '<', $value2],
    ['column_name3', '>', $value3]
])->get();

你也可以这样使用,

$results = User::orderBy('id','DESC');
$results = $results->where('column1','=', $value1);
$results = $results->where('column2','<',  $value2);
$results = $results->where('column3','>',  $value3);
$results = $results->get();

答案 13 :(得分:2)

没有一个真实的例子,很难提出建议。但是,我从来不需要在查询中使用那么多WHERE子句,这可能表明数据结构存在问题。

了解数据规范化可能会有所帮助: http://en.wikipedia.org/wiki/Third_normal_form

答案 14 :(得分:2)

使用Eloquent,很容易创建多个where检查:

首先:(在此处简单使用)

$users = User::where('name', $request['name'])
    ->where('surname', $request['surname'])
    ->where('address', $request['address'])
    ...
    ->get();

第二个:(将您的位置分组在数组中)

$users = User::where([
    ['name', $request['name']],
    ['surname', $request['surname']],
    ['address', $request['address']],
    ...
])->get();

您也可以在其中使用条件(=,<>等):

$users = User::where('name', '=', $request['name'])
    ->where('surname', '=', $request['surname'])
    ->where('address', '<>', $request['address'])
    ...
    ->get();

答案 15 :(得分:2)

代码示例。

首先:

change(_:)

数组使用所需的条件计数/循环递增地填充到这里:

callAsFunction(_:)

再加上像这样的收缩表达的口才:

// inside the struct declaration:
mutating func callAsFunction(_ closure: (inout AnimationViewConfiguration) -> Void) {
        closure(&self)
    }
// ...
// using the struct:

var mainBackgroundAnimationViewConfig = AnimationViewConfiguration()

mainBackgroundAnimationViewConfig {
    $0.contentMode = 0
    $0.mainTitle = "Your super animation"
    $0.subTitle = "A subtitle anyway"
    $0.alternativeSubtitle = "Hey another one!"
}

答案 16 :(得分:1)

您可以在where子句中使用array,如下所示。

$result=DB::table('users')->where(array(
'column1' => value1,
'column2' => value2,
'column3' => value3))
->get();

答案 17 :(得分:0)

在 Eloquent 中你可以试试这个:

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

答案 18 :(得分:0)

我们使用此指令根据用户分类的类型和用户名的两个条件来获取用户。

除了从个人档案表中获取用户信息以减少查询数量外,我们在键入时还使用了两种过滤条件。

$users = $this->user->where([
                    ['name','LIKE','%'.$request->name.'%'],
                    ['trainers_id','=',$request->trainers_id]
                    ])->with('profiles')->paginate(10);

答案 19 :(得分:0)

如果您的条件是这样的(匹配单个值),则一个简单而优雅的方法将是:

$results = User::where([
         'this' => value,
         'that' => value,
         'this_too' => value,
          ...
      ])
    ->get();

但是如果您需要对这些子句进行OR运算,请确保为每个orWhere()子句重复必须满足的条件。

    $player = Player::where([
            'name' => $name,
            'team_id' => $team_id
        ])
        ->orWhere([
            ['nickname', $nickname],
            ['team_id', $team_id]
        ])

答案 20 :(得分:0)

使用纯Eloquent,像这样实现它。此代码返回其帐户处于活动状态的所有登录用户。   $users = \App\User::where('status', 'active')->where('logged_in', true)->get();

答案 21 :(得分:0)

使用此

$users = DB::table('users')
                    ->where('votes', '>', 100)
                    ->orWhere('name', 'John')
                    ->get();

答案 22 :(得分:0)

根据我的建议,如果您要进行过滤或搜索

那你应该选择:

        $results = User::query();
        $results->when($request->that, function ($q) use ($request) {
            $q->where('that', $request->that);
        });
        $results->when($request->this, function ($q) use ($request) {
            $q->where('this', $request->that);
        });
        $results->when($request->this_too, function ($q) use ($request) {
            $q->where('this_too', $request->that);
        });
        $results->get();

答案 23 :(得分:0)

DB::table('users')
            ->where('name', '=', 'John')
            ->orWhere(function ($query) {
                $query->where('votes', '>', 100)
                      ->where('title', '<>', 'Admin');
            })
            ->get();

答案 24 :(得分:-1)

您可以按照以下方式进行,这是最短的方法。

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

答案 25 :(得分:-3)

public function search()
{
    if (isset($_GET) && !empty($_GET))
    {
        $prepareQuery = '';
        foreach ($_GET as $key => $data)
        {
            if ($data)
            {
                $prepareQuery.=$key . ' = "' . $data . '" OR ';
            }
        }
        $query = substr($prepareQuery, 0, -3);
        if ($query)
            $model = Businesses::whereRaw($query)->get();
        else
            $model = Businesses::get();

        return view('pages.search', compact('model', 'model'));
    }
}

答案 26 :(得分:-19)

$variable = array('this' => 1,
                    'that' => 1
                    'that' => 1,
                    'this_too' => 1,
                    'that_too' => 1,
                    'this_as_well' => 1,
                    'that_as_well' => 1,
                    'this_one_too' => 1,
                    'that_one_too' => 1,
                    'this_one_as_well' => 1,
                    'that_one_as_well' => 1);

foreach ($variable as $key => $value) {
    User::where($key, '=', $value);
}