简体   繁体   中英

Multiple Find Query in single database connection Laravel

Trying to enhance performance in Laravel query. Making multiple find operations on a single model, withing a loop, but trying to make it use a single database connection instance.

$departments = [];

foreach ($this->departments_only as $department) {
    array_push($departments, Department::find($department));
}

return $departments;

No error. But just want a better performance.

As I can see the departments_only is array of ids, so you can use whereIn

$departments = Department::whereIn('id', $this->departments_only)->get();

This will return collection of departments .

For these cases, I use this library l5-repository

And do it:

$myArray = [1,2,3,4];

$result = $this->repository->scopeQuery(function ($query) use ($myArray) {
            return $query
                ->whereIn("departament_id", $myArray);
        })->all();

return $result

Or using raw queries and pure Laravel:

$myArray = [1,2,3,4,5];

$result = DB::table('departments')
                ->selectRaw('departament_id in (?)', $myArray)
                ->get();

if $this->departments_only has only ids in array then you can use

Model::whereIn('column','array')->get();

For more reference visit https://laravel.com/docs/5.8/queries#where-clauses

Or use DB object as,

DB::statement('SELECT * FROM table_name WHERE column_name IN ('"array_of_ids"')');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM