In Laravel is it possible that we should use distinct() with wherein()?
$patients = Patient::whereIn('id', [1, 2, 3, 5, 6, 9])->get(); $groupby_patients = $patients->groupBy('gender');
In the $patients
query, the distinct() is not working with whereIn()
and I want to use distinct() in my query(), I do not want to get all-male patients and I want to select just one in the male group or just one in the female group like the example given below.
Example:
IlluminateSupportCollection {#2319 ▼ #items: array:2 [ male, female ] }
Any help would be appreciated.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
2 rows are considered distinct if none of the columns match in the columns selected.
For example, if we had the following patients:
id | name | gender |
---|---|---|
5 | “John” | male |
5 | “John” | male |
10 | “Bob” | male |
20 | “Jamie” | male |
25 | “Jamie” | female |
And we did:
Patient::select('name', 'gender')->distinct()->get();
We would get:
name | gender |
---|---|
“John” | male |
“Bob” | male |
“Jamie” | male |
“Jamie” | female |
Therefore it does not seem to be suitable for your use case.
This would be an efficient way of performing your query:
$genders = ['male', 'female'];
// $genders = Patient::select('gender')->distinct(); // If you want to dynamically fetch the genders.
$patients = collect();
foreach($genders as $gender) {
$patient = Patient::whereIn('id', [1, 2, 3, 5, 6, 9])->where('gender', $gender)->first();
if ($patient !== null) {
$patients->push($patient);
}
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0