2017-03-03 71 views
-1

目的

我想获得总指的是单个用户的所有用户之间的共同利益,使用雄辩关系,而不是直接查询生成器我该怎么做这个与雄辩关系的连接表?

表结构

用户

+----+--------+ 
| id | name | 
+----+--------+ 
| 1 | John | 
| 2 | George | 
| 3 | Paul | 
+----+--------+ 

利益

+----+-----------+ 
| id | name | 
+----+-----------+ 
| 1 | apple  | 
| 2 | banana | 
| 3 | pineapple | 
+----+-----------+ 

users_interests

+--------+------------+ 
| userId | interestId | 
+--------+------------+ 
|  1 |   1 | 
|  1 |   2 | 
|  1 |   3 | 
|  2 |   1 | 
|  2 |   2 | 
|  3 |   1 | 
+--------+------------+ 

类似的东西...

[ 
    { 
     "id": 2, 
     "name": "George", 
     "mutualInterests": 2, 
    }, 
    { 
     "id": 3, 
     "name": "Paul", 
     "mutualInterests": 1, 
    } 
] 

回答

0

在用户模式

public function interests() 
{ 
    return $this->belongsToMany('App\Interest'); 
} 

在你的兴趣模型现在

public function users() 
{ 
    return $this->belongsToMany('App\User'); 
} 

在您的控制器功能

$users = User::all(); 

现在在您的视图中获取您的每个用户的所有感兴趣数量。

@foreach($users as $user) 
     {{ $user->interests()->count() }} 
     <!-- if you need to extract all interests then --> 
     @foreach($user->interests as $interest) 
        {{ $interest->name }} 
     @endforeach 
    @endforeach 

根据您的评论的更新看到共同的利益算过

@foreach($users as $user) 
     {{ $user->interests()->count() }} 
     <!-- if you need to extract all interests then --> 
     <?php $mutualInterest= 0; ?> 
     @foreach($user->interests as $interest) 
        <?php 
         $check = checkfunction($interest->id); 
         if($check == TRUE){ 
           $mutualInterest = $mutualInterest+1; 
         } 

        ?> 
        {{ $interest->name }} 
     @endforeach 
     <?php echo "Mutual Intersts".$mutualInterest; ?> 
@endforeach 

现在检查功能,在你看来

<?php 
function checkfunction($id){ 
    $interest = App\Interest::find($id); 

    if($interest->users()->count()>1){ 
     return true; 
    }else{ 
     return false; 
    } 

} 
?> 
+0

谢谢您的回答的底部。 在你的例子中,我会分别得到每个用户的兴趣总数。但我的建议是获得与单个用户共同的兴趣数量。例如,乔治与约翰有两个共同的兴趣。我想知道乔治的细节和他们共同的兴趣总数。 –

+0

@IsaacFerreira我编辑了答案。请再试一次 –

+0

@IsaacFerreira上面的解决方案为您工作。 –