Good day,
I wanted to do something like this:
$ids = [1, 2, 3];
$posts = $user->posts()->whereIn('id', $ids)->get();
but I get an Internal Server Error. Is there a different way to do this?
For the sake of this example, assume ID is not the primary key and that multiple posts can have the same ID. So this:
$ids = [1, 2, 3];
$posts = Post::whereIn('id', $ids)->get();
wouldn't return the desired results.
The reason you are having the error is mysql is unable to what table you are referring with id column. Use tableName in whereIn() clouse
$posts = $user->posts()->whereIn('posts.id', $ids)->get();
N.B: I assume your Post table name is posts
please use like
$items = DB::table('items')->whereIn('id', [1, 2, 3])->get();
link : Laravel ->where('id', ARRAY). multiple where conditions laravel 4
And
User::select('id','name','email','phone','created_at')->whereIN('id',[1,2,3,4,5,6,7,8,9,9,10,11])->where('is_guest',NULL)->where('user_type','1')->orderBy('id','desc')->take(20)->get();
also work with laravel 5.4
Related
I want to make query in Laravel Eloquent like here its raw MySQL query
SELECT * from exampleTbl where id in(1,2,3,4)
I have tried this in Laravel Eloquent but it's not working
DB::where("id IN(23,25)")->get()
Here is how you do in Eloquent
$users = User::whereIn('id', array(1, 2, 3))->get();
And if you are using Query builder then :
$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();
If you are using Query builder then you may use a blow
DB::table(Newsletter Subscription)
->select('*')
->whereIn('id', $send_users_list)
->get()
If you are working with Eloquent then you can use as below
$sendUsersList = Newsletter Subscription:: select ('*')
->whereIn('id', $send_users_list)
->get();
Syntax:
$data = Model::whereIn('field_name', [1, 2, 3])->get();
Use for Users Model
$usersList = Users::whereIn('id', [1, 2, 3])->get();
As #Raheel Answered it will be fine but if you are working with Laravel 6/7
Then use Eloquent whereIn Query.
Example1:
$users = User::wherein('id',[1,2,3])->get();
Example2:
$users = DB::table('users')->whereIn('id', [1, 2, 3])->get();
Example3:
$ids = [1,2,3];
$users = User::wherein('id',$ids)->get();
Since Laravel 5.7, there is a method whereIntegerInRaw. The execution time is faster than whereIn.
User::whereIn('id', [1, 2, 3])->get();
User::whereIntegerInRaw('id', [1, 2, 3])->get();
You can see the PR.
Maybe you wanna use whereRaw($query)
Your Code :
DB::where("id IN(23,25)")->get()
Into :
DB::whereRaw("id IN(23,25)")->get()
Hello I have a table ideas and I want to return the rows where the user_id = with the authenticated user id plus the rows where category_id = lets suppose is array [1, 2, 3].
Disclaimer: i want both of the conditions to be returned!
Seems like that:
i think that your table ideas and model Idea associated with this have the next structure:
id, user_id, category_id and some other fields...
To get Authenticated user you can do Auth::user();
So, you can do something like this:
$categoryIds = [1, 2, 3];
$authUserId = Auth::user()->id;
$ideas = Idea::where('user_id', $authUserId)->whereIn('category_id', $categoryIds)->get();
If you need relations to be extracted with the query you can add with statement:
$ideas = Idea::with('categories')->where('user_id', $authUserId)->whereIn('category_id', $categoryIds)->get();
ofc, you need to set realtions in your models
Also you can set relation in user model and get records associated with the user:
User.php
public function ideas() {
return $this->hasMany('App\Idea');
}
somewhere in code:
$categoryIds = [1, 2, 3];
Auth()->user()->ideas()->whereIn('category_id', $categoryIds)->get();
UPDATE:
To do some form of join you can use this:
$userIdeas = Idea::where('user_id', Auth::user()->id)->get();
$categoryIds = [1, 2, 3];
$categoryIdeas = Idea::where('user_id', '<>', Auth::user()->id)->whereId('category_id', $categoryIds)->get();
$mergedIdeas = $userIdeas->merge($categoryIdeas);
AND AT LAST. To do it in one query:
$userId = Auth::user()->id;
$categoryIds = [1, 2, 3];
$ideas = Idea::where('user_id', $userId)->orWhere(function($query) use ($categoryIds) {
$query->where('user_id', '<>', $userId)->whereIn('category_id', $categoryIds);
})->get();
Im having a bit of a problem knowing what you want but
If you want the results for authenticated users id and category ids you could
$category_ids = [1, 2, 3];
$model->where('category_id', auth()->user->id)->whereIn('user_id', $ids)->get();
If you want the results for either the authenticated user or where the category_ids is in the array you could
$category_ids = [1,2,3];
$model->orWhere(function($q) use($category_ids) {
$q->where('category_id', auth()->user->id);
$q->whereIn('user_id', $category_ids);
})->get();
Note that this will break if the user is not authed, but I leave that to you to do.
This question already has answers here:
Sorting Laravel Collection via Array of ID's
(3 answers)
Closed last year.
I have an array of ID's as follows:
$ids = [5,6,0,1]
Using Eloquent I am able to search for these Id's using the ->whereIn('id', $ids) function. This as expected will return the results in the ascending order by Id, is there a way I can return the results on the order the array is in? alternatively whats the easiest way to convert the collection in the order of the $ids array?
If there's a specific order you'd like the records in, you'd have to use the Collection Methods:
To get your ID's in the very specific order you've specified, you can make use of the sortBy method as follows, where collection is your collection of models:
$ids = [ 5, 6, 0, 1];
$sorted = $collection->sortBy(function($model) use ($ids) {
return array_search($model->getKey(), $ids);
});
// [ 5, 6, 0, 1] // (desired order)
To randomize your collection you can make use of the shuffle method.
$collection = collect([1, 2, 3, 4, 5]);
$shuffled = $collection->shuffle();
$shuffled->all();
// [3, 2, 5, 1, 4] // (generated randomly)
See the Laravel Docs on shuffle and/or sortBy for more specific requirements.
If you don't really have a specific order in mind, you can use ->inRandomOrder() in version 5.2 and up, older versions would require the raw query using ->orderBy(DB::raw('RAND()')).
See answer to MySQL order by field in Eloquent. It is possible to order the data in your SQL query. Other answers here are suggesting you sort the data after you've already fetched it in "wrong" order.
Your code should look like this:
$ids = [5,6,0,1];
$collection = YourModel::whereIn('id', $ids)
->orderByRaw('FIELD (id, ' . implode(', ', $ids) . ') ASC')
->get();
You can pass a function into the sortBy method to perform complex sorting:
$ids = [5,6,0,1];
$collection = YourModel::whereIn('id', $ids)->sortBy(function($model) use ($ids) {
// Access your array order here and modify the sorting here
});
I just wanted to know if it's possible.
I know when you have multiple rows to insert, you can just build an array and do something like:
DB::table('some_table')->insert($array);
But as far as I've read, doing the same for deleting doesn't seem to be possible, I'd like to know if anyone know of a way to do something like:
DB::table('some_table')->delete($array);
Many ways of deleting records in Laravel 4.1
1) When you want to delete records from your database, simply call the delete method:
$affected = DB::table('users')->where('id', '=', 1)->delete();
2) Want to quickly delete a record by its ID? No problem. Just pass the ID into the delete method:
$affected = DB::table('users')->delete(1);
3) If you want to delete multiple records by id at once, passing their ids in an array - use the following
$users_to_delete = array(1, 2, 3);
DB::table('users')->whereIn('id', $users_to_delete)->delete();
4) If you want to delete multiple records by id at once, passing an array of users - use the following
//(case A) User fields indexed by number 0,1,2..
$users_to_delete = array(
'0'=> array('1','Frank','Smith','Whatever'),
'1'=> array('5','John','Johnson','Whateverelse'),
);
$ids_to_delete = array_map(function($item){ return $item[0]; }, $users_to_delete);
DB::table('users')->whereIn('id', $ids_to_delete)->delete();
//(case B) User fields indexed by key
$users_to_delete = array(
'0'=> array('id'=>'1','name'=>'Frank','surname'=>'Smith','title'=>'Whatever'),
'1'=> array('id'=>'5','name'=>'John','surname'=>'Johnson','title'=>'Whateverelse'),
);
$ids_to_delete = array_map(function($item){ return $item['id']; }, $users_to_delete);
DB::table('users')->whereIn('id', $ids_to_delete)->delete();
5) Deleting An Existing Model By Key
User::destroy(1);
User::destroy(array(1, 2, 3));
User::destroy(1, 2, 3);
6) Of course, you may also run a delete query on a set of models:
$affectedRows = User::where('votes', '>', 100)->delete();
I've got a Laravel model, but i'd like to search the table according to an array passed in.
i.e. "Return all rows whose id matches one of the array's contents"
I can see with Laravel's query builder i can search via an input array:
$users = DB::table('teams')->whereIn('id', array(1, 2, 3))->get();
But can't seem to find anywhere how to do the same using a model.
Any ideas? Cheers!
Replace DB::table('teams')-> with a static call to the model.
$users = <model name>::whereIn('id', array(1, 2, 3))->get();
You can try this.
<?php
use App\Models\Team;
$users = Team::whereIn('id', array(1, 2, 3))->get();