Can I do Model->where('id', ARRAY) multiple where conditions?
PhpLaravelPhp Problem Overview
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?
Php Solutions
Solution 1 - Php
There's whereIn()
:
$items = DB::table('items')->whereIn('id', [1, 2, 3])->get();
Solution 2 - Php
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();
Solution 3 - Php
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();
Solution 4 - Php
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();
Solution 5 - Php
If you are searching by ID you can also use:
$items = Item::find(array_of_ids);
Solution 6 - Php
$whereData = [['name', 'test'], ['id', '<>', '5']];
$users = DB::table('users')->where($whereData)->get();
Solution 7 - Php
WHERE AND SELECT Condition In Array Format Laravel
use DB;
$conditions = array(
array('email', '=', '[email protected]')
);
$selected = array('id','name','email','mobile','created');
$result = DB::table('users')->select($selected)->where($conditions)->get();