0

I have a query that take 10 ids, then I'm looping thorugh those id's, using foreach to execute seperate queries for each id. But I'm getting more queries, for each loop it's adding previous ones too, I don't get why. I use Laravel 5.

foreach($data as $id)
{
     $query = (new TestModel)->newQuery();
     $query->where('Test.ID', '=', $id);
}

When I get query log, for first loop I have one query, for second loop I have two queries and so on. But when I just echo $id, it's showing exactly right number of ids.

4 Answers 4

2

I will suggest you to use whereIn() of laravel query builder

// It will give you all queries
$allQueries = TestModel::whereIn('id',$data)->get();

then you can iterate throught foreach to get your query

foreach($allQuery as $query)
{ 
 // Here $query will return single object of TestModel
 // do your stuff here.
}

For your question what we discussed in comment. Try this

$allQueries = TestModel::whereIn('id',$data)->get();
$groupByQuery = collect($allQueries)->groupBy('date')->toArray();

return $groupByQuery;

see is it returning what you want.?

Sign up to request clarification or add additional context in comments.

4 Comments

but this doenst work for me, for your example is working,but I'm adding groub by and in this case it's working wrong.I think I need to write query inside foreach for grouping data and taking whatever I want
No, this will group for all rows, but I need to group by each id's date
If you will fetch TestModel::where('id',$id)->get(); then it will return single result, right ? but groupBy is used on more than one results like array or array of objects, then how you want to implement it for a single result.?
@LusineMartirosyan Try this. If it doesn't work then you can email me your DB tables schema and your exact problem at [email protected]
1

Move your your instantiation of $query outside your loop.

$query = (new TestModel)->newQuery();
foreach($data as $id)
{
     $query->where('Test.ID', '=', $id);
}

Or better, just use whereIn:

$query = (new TestModel)->newQuery()->whereIn('Test.ID', $data);

You don't even need to instantiate a new model:

$query = TestModel::whereIn('Test.ID', $data);

Comments

0

Guess you should add

unset($query);

As you create a new query everytime.

1 Comment

Thanks for your answer, but the same. It's showing multiple queries in debug
0

Try using eloquent model:

foreach($data as $id)
{
     $query = TestModel::Where('Test.ID', '=', $id)->get();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.