如何使用Eloquent Relationships进行此连接表?

时间:2017-03-03 18:15:07

标签: php mysql laravel eloquent relationships

目的

我希望直接使用雄辩的关系而不是查询构建器,在所有引用单个用户的用户之间获得共同兴趣。

表结构

用户

+----+--------+
| 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,
    }
]

1 个答案:

答案 0 :(得分: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;
    }

}
?>