Can I do Model->where('id', ARRAY) multipl

2019-01-22 07:06发布

问题:

The title says it all.

I get that I can do this :

DB:table('items')->where('something', 'value')->get()

But what I want to check the where condition for multiple values like so:

DB:table('items')->where('something', 'array_of_value')->get()

Is there an easy way of doing this?

回答1:

There's whereIn():

$items = DB::table('items')->whereIn('id', [1, 2, 3])->get();


回答2:

If you need by several params:

$ids = [1,2,3,4];
$not_ids = [5,6,7,8];
DB::table('table')->whereIn('id', $ids)
                  ->whereNotIn('id', $not_ids)
                  ->where('status', 1)
                  ->get();


回答3:

You can use whereIn which accepts an array as second paramter.

DB:table('table')
   ->whereIn('column', [value, value, value])
   ->get()

You can chain where multiple times.

DB:table('table')->where('column', 'operator', 'value')
    ->where('column', 'operator', 'value')
    ->where('column', 'operator', 'value')
    ->get();

This will use AND operator. if you need OR you can use orWhere method.

For advanced where statements

DB::table('table')
    ->where('column', 'operator', 'value')
    ->orWhere(function($query)
    {
        $query->where('column', 'operator', 'value')
            ->where('column', 'operator', 'value');
    })
    ->get();


回答4:

You could use one of the below solutions:

$items = Item::whereIn('id', [1,2,..])->get();

or:

$items = DB::table('items')->whereIn('id',[1,2,..])->get();