【问题标题】:How can I do this join-table with Eloquent Relationships?我怎样才能用雄辩的关系做这个连接表?
【发布时间】:2017-07-23 23:22:51
【问题描述】:

目的

我想直接使用 Eloquent Relations 而不是 Query Builder 来获取所有引用单个用户的用户之间的共同兴趣。

表结构

用户

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

【问题讨论】:

    标签: php mysql laravel eloquent relationships


    【解决方案1】:

    在您的用户模型中

    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;
        }
    
    }
    ?>
    

    【讨论】:

    • 感谢您的回答。在您的示例中,我将分别获取每个用户的兴趣总数。但我的建议是获得与单个用户相同的兴趣数量。例如,乔治与约翰有两个共同点。我想了解 George 的详细信息以及他们共同感兴趣的总数。
    • @IsaacFerreira 我编辑了答案。请再试一次
    猜你喜欢
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 2017-04-04
    • 2020-04-25
    • 2012-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多