Can I do Model->where('id', ARRAY) multiple where conditions? - php

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?

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

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

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

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

If you are searching by ID you can also use:
$items = Item::find(array_of_ids);

It's work for me
fetch just id then search in array
$shops = Shop::Where('user_id', Auth::id())->get('id');
$categories = Category::whereIn('shop_id',$shops)->paginate(7);

$whereData = [['name', 'test'], ['id', '<>', '5']];
$users = DB::table('users')->where($whereData)->get();

WHERE AND SELECT Condition In Array Format Laravel
use DB;
$conditions = array(
array('email', '=', 'user#gmail.com')
);
$selected = array('id','name','email','mobile','created');
$result = DB::table('users')->select($selected)->where($conditions)->get();

Related

Combing multiple orWhere() in Laravel 9 Eloquent

Is it possible to combine multiple orWhere() inside one where()?
E.g. The following:
$query->where(function($query){
$query->where('text1', '=', $_GET['lorem'])
->orWhere('text2', '=', $_GET['lorem'])
->orWhere('text3', '=', $_GET['lorem'])
->orWhere('text4', '=', $_GET['lorem']);
});
Would look something like this:
$query->where(function($query){
$query->where(['text1' || 'text2' || 'text3' || 'text4'], '=', $_GET['lorem']);
});
P.S. In the above hypothetical example, the [ ] aren't really referring to an array but I'm just using the brackets to group text1/2/3/4.
$query->where(function($query){
$columns = ['text1', 'text2', 'text3'];
foreach($columns as $column){
$query->OrWhere($column, '=', $_GET['lorem']);}});
This might work
Try this...
$columns = ['text1', 'text2', 'text3'];
$query->where(function ($query) use ($columns) {
foreach ($columns as $key => $column) {
if ($key == 0) $query->where($column, '=', $_GET['lorem']);
else $query->OrWhere($column, '=', $_GET['lorem']);
}
});
It looks like the documentation for this actually does allow you to pass an array of equal statements in a key-value arrangement.
$columns = [
'text1'=>$value,
'text2'=>$value,
'text3'=>$value
];
$query->where($columns);
You can see this works from the laravel docs in 9.X
https://github.com/laravel/framework/blob/29430b413b29fb60073ad26682a572df2ab5f5b2/src/Illuminate/Database/Query/Builder.php#L703
This shows the builder where clause. Following this, are the lines 708-710 which take the array and make it into the looped where statement that has been a solution for you up until now.
Please note that this method seems to only work with '=' as far as I can see.
TLDR:
Put key-value array into first param of where method.

Order and Sub Order collection - laravel 7 (Simple)

lets say I have a collection of users Users::all()
I would like to take sort/order it like such Users::all()->sort('created_at', 'DESC')
then I would like to sub order it by an array like [1,5,3,9,4,8] so perhpas a call like this Users::all()->sort('created_at', 'DESC')->sortBy("id", [1,5,3,9,4,8])
Any Advice?
Edit 1
I have found this, is this correct to use?
$ids = collect([1,5,3,9,4,8]);
$users = Users::all()->sort('created_at', 'DESC');
$users = $ids->map(function($id) use($users) {
return $users->where('cat_id', $id)->first();
});
I think you could just invoke orderBy() twice.
$ids = [1,5,3,9,4,8];
$users = Users::all()
->orderBy('created_at', 'desc')
->orderBy($ids)
->get();
Does this answer your question?
You can use whereIn like this probably:
$ids = [1,5,3,9,4,8];
$users = Users::all()
->orderBy('created_at', 'desc')
->whereIn('cat_id', $ids)
->get();
https://laravel.com/docs/9.x/queries#additional-where-clauses
The whereIn method verifies that a given column's value is contained within the given array
So I found a solution.
$ids = json_decode($interview->question_ids ?? '[]');
if(count($ids) == 0){ // if empty create new id array and save to DB
$ids = collect(questions::all()->where('interview_id', $interview->id)->pluck('id')->toArray());
$interview->question_ids = json_encode($ids);
$interview->save();
}
$questions = questions::all()->where('interview_id', $interview->id)->sortBy([
['order_timestamp', 'asc'],
['created_at', 'asc'],
]);
$questions = $ids->map(function($id) use($questions) {
return $questions->where('id', $id)->first();
});
$questions = $questions->flatten();

Laravel order by for each column?

I am new to laravel, and i try to orderBy the rand, is it possible to order by in each column ? my code just take row rand but it dont shuffle the column just the row.
public function show(){
$name = DB::table('names')
->inRandomOrder()
->get();
return view('content', ['names' => $names]);
}
orderBy in Laravel.
The orderBy method allows you to sort the result of the query by a given column. The first argument to the orderBy method should be the column you wish to sort by, while the second argument controls the direction of the sort and may be either asc or desc:
$users = DB::table('users')
->orderBy('name', 'desc')
->get();
In your case this will work.
public function show(){
$names = DB::table('names')
->orderBy('name', 'desc')
->orderBy('city', 'asc')
->get();
return view('content', ['names' => $names]);
You Can Do Like This For To Order by in each column
public function show(){
$names = DB::table('names')
->orderBy('name', 'DESC')
->orderBy('city', 'DESC')
->orderBy('email', 'ASC')
->get();
return view('content', ['names' => $names]);
}
With foreach
$names = DB::table('names');
foreach ($request->get('order_by_columns') as $column => $direct) {
$names->orderBy($column, $direct);
}
$results = $names->get();

Count from other table

I am having problem to count number of devices where guid is not null.
It need to get all the shops by user user_id and then count all the devices where guid is not null.
$shops = Shop::with('devices')->where('user_id', $userId)->get();
$deviceActive = $shops->reduce(function ($carry, $item) {
return $carry + $item->devices->whereNotNull('guid')->count();
});
dd($deviceActive );
It work when I do:
return $carry + $item->devices->count();
but it need to count where guid is not null.
I would also be interested to hear if there is alternative reduce approach.
Since $item->devices is a collection there is no whereNotNull() for collections. So try to use where():
$item->devices->where('guid', '<>', null)->count();
Try:
$shops = Shop::with('devices')
->where('user_id', $userId)
->where('guid', '!=', null)->get();
$get_count = count($shops); // it return how many values have $shops
OR
$shops= DB::table('devices')->where('user_id', $userId)
->where('guid', '!=', null)->get();
$get_count = count($shops);
if you did not have the class DB add at your controller:
use DB;

Query Laravel Select WhereIn Array

This query does not work correctly, it only shows 1 row
$data = Post::select('id', 'name')
->whereIn('id', [$order])
->orderByRaw(\DB::raw("FIELD(id, $order)"))
->get();
but this works fine, it shows all rows
$data = Post::select('id', 'name')
->whereIn('id', [1,2,3])
->orderByRaw(\DB::raw("FIELD(id, $order)"))
->get();
Thank you!
Your Query is Here:-
$data = Post::select('id', 'name')
->whereIn('id', $order)
->orderByRaw(\DB::raw("FIELD(id, ".implode(",",$order).")"))
->get();
Remove [] from $order.
For WhereIn condition second parameter should be an array. So the $order should be
$order = [1,2,3,4]
If your $order is an array, i think that you should do this
whereIn('id', $order) instead of whereIn('id', [$order])
P.S. In official documentation mentioned that second argument should be an array:
$users = DB::table('users')
->whereIn('id', [1, 2, 3])
->get();

Categories