如何通过laravel query

时间:2017-07-11 05:27:05

标签: mysql sql laravel laravel-query-builder

我有这个SQL查询来获得至少3个共同兴趣的用户。

$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']) ));

如何将上述sql查询翻译成laravel eloquent查询?

2 个答案:

答案 0 :(得分:1)

这样的事情应该有效

$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')_;

或完全雄辩的版本(由于我不知道你的模型,不得不使用DB而不是模型)

$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();

答案 1 :(得分:1)

以下查询将执行此操作

$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();