MySQL Query查找已经不是朋友的用户,并按共同的朋友计数

时间:2015-01-06 14:53:03

标签: php mysql laravel-4

我在Laravel 4.2中有一个社交网站类型的网站。

基本用户表...

一张存储友谊的表格叫做" connections"

Connections
___________

user1_id
user2_id
status ('approved' or 'pending')

我正在努力弄清楚如何通过共同计数获取用户和订购。

我正在尝试构建一个页面,显示推荐的朋友列表,这正是我上面所描述的。

我对Laravel来说相当新......但我会说这更像是一个SQL问题。任何帮助表示赞赏。

以下是我用于其他搜索页面的一些代码..但这仅用于比较2个用户,因此它可能会对您有所帮助。

public function mutualFriendCount($user1Id, $user2Id)
{
    $user1Friends = array();
    $user2Friends = array();

    //build array of friends for user1 and user2 
    $user1Connections = Connection::whereStatus('approved')
        ->where(function($query) use($user1Id){
           $query->orWhere('user1_id', '=', $user1Id);
           $query->orWhere('user2_id', '=', $user1Id);
        })->orderBy('created_at')->select('user1_id' , 'user2_id')->get();


    foreach ($user1Connections as $user1Connection) {
        if($user1Connection->user1_id != $user1Id && $user1Connection->user1_id != $user2Id) {
            $user1Friends[] = $user1Connection->user1_id;
        }
        if($user1Connection->user2_id != $user1Id && $user1Connection->user2_id != $user2Id) {
            $user1Friends[] = $user1Connection->user2_id;
        }
    }

    $user2Connections = Connection::whereStatus('approved')
        ->where(function($query) use($user2Id){
           $query->orWhere('user1_id', '=', $user2Id);
           $query->orWhere('user2_id', '=', $user2Id);
        })->orderBy('created_at')->select('user1_id' , 'user2_id')->get();


    foreach ($user2Connections as $user2Connection) {
        if($user2Connection->user1_id != $user1Id && $user2Connection->user1_id != $user2Id) {
            $user2Friends[] = $user2Connection->user1_id;
        }
        if($user2Connection->user2_id != $user1Id && $user2Connection->user2_id != $user2Id) {
            $user2Friends[] = $user2Connection->user2_id;
        }
    }

    //compare the arrays and return the count
    return count(array_intersect($user1Friends, $user2Friends));

}

0 个答案:

没有答案