Home  >  Article  >  PHP Framework  >  How to use laravel orWhere? (with code example)

How to use laravel orWhere? (with code example)

藏色散人
藏色散人forward
2022-01-04 14:42:055026browse

The following tutorial column from Laravel will explain how to use laravel orWhere. I hope it will be helpful to everyone!

The where condition query under the laravel framework is very simple, so I won’t write it here. Here I mainly record the splicing of the orWhere multi-condition or query statement that is not commonly used. The example is as follows:

(1 ) SQL statement:

select `id` from `user` where (`email` = 'admin@phpernote.com' and `password` = '123456') or (`mobile` = '13681127231' and `password` = '123456');

laravel model statement:

User::select(['id'])
    ->where(function ($query) use ($userName, $password) {
        $query->where('password', '=', '123456')->where('email', '=', 'admin@phpernote.com');
    })
    ->orWhere(function ($query) use ($userName, $password) {
        $query->where('password', '=', '123456')->where('mobile', '=', '13681127231');
    })
    ->first();

(2) SQL statement:

select count(*) from `user` where `type` = 1 and `valid_type` = 2 and (`valid_end` < 1560738570 or `valid_begin` > 1560738570);

laravel model statement:

$model = User::where(&#39;type&#39;, 1)->where(&#39;valid_type&#39;, &#39;=&#39;, 2)->where(function ($query) {
    $query->where(&#39;valid_end&#39;, &#39;<&#39;, 1560738570)->orWhere(function ($query) {
        $query->where(&#39;valid_begin&#39;, &#39;>&#39;, 1560738570);
    });
})->first();

(3) SQL Statement:

select count(*) from `user` where `valid_type` = 2 or (`valid_type` = 3 and (`valid_end` < 1560738570 or `valid_begin` > 1560738570));

laravel model Statement:

$model = User::where(function ($query) {
    $query->where(&#39;valid_type&#39;, 2);
})->orWhere(function ($query) {
    $query->where(&#39;valid_type&#39;, &#39;=&#39;, 3)->where(function ($query) {
        $query->where(&#39;valid_end&#39;, &#39;<&#39;, 1560738570)->orWhere(function ($query) {
            $query->where(&#39;valid_begin&#39;, &#39;>&#39;, 1560738570);
        });
    });
})->first();

Related recommendations: The latest five Laravel video tutorials

The above is the detailed content of How to use laravel orWhere? (with code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:phpernote.com. If there is any infringement, please contact admin@php.cn delete