【问题标题】:Laravel relationship mutual matching (tinder case)Laravel 关系相互匹配(火种案例)
【发布时间】:2019-08-13 04:36:09
【问题描述】:

我在 Laravel 中应用关系,我正在尝试将它们应用到“我喜欢”系统中,很容易使关系成为一对多,但我希望在相互匹配方面有所帮助;对于这样的系统,通过将用户作为参数传递来获得相互匹配的最佳选择是什么。

用户

|id | name        | gender |
+---+-------------+--------+
| 1 | John Kenedy | male   |
| 2 | Meresa Oslo | female |
| 3 | Mike Lanes  | male   |

喜欢

|id | user_id | user_liked_id |
+---+---------+---------------+
| 1 |    1    |       2       | //matching with 2
| 2 |    1    |       3       | //likes
| 3 |    2    |       1       | //matching with 1

得到它会是这样的:

User::find(1)->matches()

我不确定我是否可以收集包含用户模型数据的集合 2

应用程序/用户.php

...

class User extends Authenticatable
{
   ...
     public function likes()
     {
       return $this->hasMany('App\Models\Like');
     }

     public function matches()
     {
       ????
     }
   ...
}

...

【问题讨论】:

    标签: php laravel laravel-5 eloquent


    【解决方案1】:

    实际上你没有一对多。上述行为是:Many-To-Many,可以这样实现:

    表 "Users_Users_liked" - 创建表 Users_Users_liked,无符号整数 'user_id',无符号整数 'user_liked_id'。 id 列是额外的,因为表 Users_Users_liked 是一个多对多数据透视表。

    然后在User类中添加关系:

    public function likesToUsers()
    {
        return $this->belongsToMany(self::class, 'Users_Users_liked', 'user_id', 'user_liked_id');
    }
    
    public function likesFromUsers()
    {
        return $this->belongsToMany(self::class, 'Users_Users_liked', 'user_liked_id', 'user_id');
    }
    
    public function matches()
    {
        return $this->likesFromUsers()->whereIn('user_id', $this->likesToUsers->keyBy('id'));
    }
    

    【讨论】:

    • 它工作完美,真的是我一直在等待的答案,在你以更好的方式完成我需要的一切之前,非常感谢
    猜你喜欢
    • 2018-12-06
    • 1970-01-01
    • 2014-05-16
    • 2021-09-29
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 2018-05-31
    • 2016-03-08
    相关资源
    最近更新 更多