Home > Software design >  Query using whereIn() not working to generate collection
Query using whereIn() not working to generate collection

Time:01-19

I have this table store_photos and I am trying to get the photos with complete raffle_date_id upto 12 and then group them by user_id. The query works but then it still generate collection even if its not complete upto 12. How can I achieve this using whereIn() or other similar eloquent?

enter image description here


    public function collection(): Collection
    {
        $months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

        return StorePhoto::with('user.location')
            ->whereIn('raffle_date_id', $months)
            ->groupBy('user_id')
            ->get();
    }

CodePudding user response:

You can try constructing the RAW SQL query, to find what you are trying to achieve. Then you can slowly build your way in Laravel.

You can try to find those users who have count of 12 (i.e. have 12 records = have 12 months). Then you can get only those users.

SELECT user_id FROM store_photos AS sp
GROUP BY sp.user_id
HAVING COUNT(sp.user_id) = 12;

Then in Laravel you can

DB::table('store_photos')
    ->groupBy('user_id')
    ->having(DB::raw('count(user_id)'), '=', 12)
    ->select('user_id');

*I do not know that much about your app and its business logic / requirement. But you get the idea :)

  •  Tags:  
  • Related