代码之家  ›  专栏  ›  技术社区  ›  Никита Дмитриевич Хорев

多对多关系。如何搜索2个集合的一个公共项?

  •  0
  • Никита Дмитриевич Хорев  · 技术社区  · 6 年前

    我在我的项目中有很多对很多的关系。 用户口碑聊天 和 与众多用户聊天。

    所以,我有一个透视表chat_user with chat_id and user_id。

    一次聊天也可以包括一些用户

    它可以,而且工作得很好。

    当我创建新聊天时,我有两个用户。我想检查一下,他们之间是否已经有了共同的谈话。

    我对这个问题有些疑问。 我还尝试在聊天室用户表上制作自定义模型,但没有运气。=( 可能有人做过这样的工作吗?有什么练习吗?谢谢您!

    2 回复  |  直到 6 年前
        1
  •  0
  •   wunch    6 年前

    一种方法是使用 whereHas() 查询生成器方法:

    $user1->chats()->whereHas('users', function($q) use ($user2) {
        $q->where('user_id', '=', $user2->id);
    })->get();
    

    作为一个最佳实践,我个人喜欢将类似的东西整合到模型(在本例中是您的聊天模型)上,作为 query scope 为了方便使用:

    // class App\Chat
    public function scopeWithUser($query, User $user)
    {
        $query->whereHas('users', function ($q) use ($user) {
            $q->where('user_id', '=', $user->id);
        });
    }
    

    然后,您可以这样使用它:

    // get common chats between user1 and user2
    $user1->chats()->withUser($user2)->get();
    
    // see if a common chat exists
    $user1->chats()->withUser($user2)->exists();
    

    我认为它可读性很强。

        2
  •  0
  •   Joel Hinz    6 年前

    最简单的方法可能是只带一个用户去找另一个。假设你的关系是正确的,就像这样:

    $firstUserChats = $firstUser->chats()->pluck('user_id');
    $usersHaveACommonChat = $firstUserChats->contains($secondUser->id);
    

    虽然在一行中有很多方法可以做到这一点,但这通常是最容易做到的。:)