Asked by: Code Guy
I have this sql query to get users with at-least 3 interest in common.
$get_similar = $db->query(sprintf('SELECT ui.user_id, COUNT( * ) AS common_interests
FROM users_interests ui
WHERE ui.interests_id
IN (
SELECT ui2.interests_id
FROM users_interests ui2
WHERE ui2.user_id = %s
)
AND ui.user_id <> %s
GROUP BY ui.user_id
HAVING common_interests >2
', secure($this->_data['user_id']), secure($this->_data['user_id']) ));
How to translate the above sql query to the laravel eloquent query?
Answers
Answered by: Rodrane at 2017-07-11 11:11AM
Something like this should work
$get_similar = \DB::raw('SELECT ui.user_id, COUNT( * ) AS common_interests
FROM users_interests ui
WHERE ui.interests_id
IN (
SELECT ui2.interests_id
FROM users_interests ui2')
->where('ui2.user_id','=', secure($this->_data['user_id']))
->where('ui.user_id','<>', secure($this->_data['user_id'])
->groupBy('ui.user_id')
->having('common_interests', '>', '2')_;
Or fully eloquent version (had to use DB instead of model since I dont know your models)
$get_similar = \DB::select('ui.user_id, COUNT( * ) AS common_interests')
->from('users_interests ui')
->whereIn('ui.interests_id', function($query) {
$query->select('ui2.interests_id')
->from('users_interests as ui2');
})
->where('ui2.user_id','=', secure($this->_data['user_id']))
->where('ui.user_id','<>', secure($this->_data['user_id'])
->groupBy('ui.user_id')
->having('common_interests', '>', '2')->get();
Answered by: Kamga Simo Junior at 2017-07-11 04:22PM Accepted
The following query will do the trick
$user_interests = User::find($user_id)->interests->pluck('id')->toArray();
$get_similar = DB::table('users_interests')
->select(DB::raw('count(*) as common_interests, user_id'))
->whereIn('interest_id', $user_interests)
->where('user_id','<>', 3)
->groupBy('user_id')
->havingRaw('COUNT(*) > 2')
->get();
No comments:
Post a Comment