Can I simplify this code without foreach?
$userQuestIds = [2,4,45,586,16,2,143,234,654,78,56];
$typeQuests = [];
foreach ($userQuestIds as $qId) {
$typeQuests[] = Quest::where(['id' => $qId])->first();
}
CodePudding user response:
If id
is a primary key the shortest way is:
$typeQuests = Quest::find($userQuestIds);
CodePudding user response:
You can use whereIn
:
$typeQuests = Quest::whereIn('id', $userQuestIds)->get();
NOTE: this approach is better for columns other than id
(as primary). I think @andriy-Lozynskiy solution is the best way.
CodePudding user response:
If you have Quest -> UserQuest relationship named 'userQuests' with table 'user_quests' you can get them like that:
$typeQuests = Quest::whereHas('userQuests', function (Builder $query) {
$query->where('user_quests.status_id', 1);
})->get();
Edit: You have simplified your question since I started answering, just keep in mind you have that option too.