Patrick Obafemi
Patrick Obafemi

Reputation: 1066

Laravel get a random user with where clause

My table schema is a id field, name field and a friends id field.

Every user must have a maximum of 2 friends. When a new user is created and event is fired and a listener which listens to the created user event then adds a random friend to a newly created user.

 $randomfriend =  DB::table('users')->select('id')
                                   ->groupBy('friends_id')
                                   ->havingRAW('COUNT(*) < 2')
                                   ->inRandomOrder()->first(); 

it still returns users with maximum number of friends. Can someone help me with this?

Upvotes: 1

Views: 358

Answers (1)

Amin.Qarabaqi
Amin.Qarabaqi

Reputation: 723

first of all create another table for friends relations. for selecting a random user this post can help you: enter link description here

don't forget to put this code in while loop for checks.

Upvotes: 2

Related Questions