【问题标题】:Laravel 5.2 - Check if conversation between 2 users existLaravel 5.2 - 检查两个用户之间的对话是否存在
【发布时间】:2016-11-19 14:15:35
【问题描述】:

我正在尝试在 Laravel 中实现一个私人消息系统,但我无法检查是否存在对话。

我有 3 张桌子:

conversations
- id

users
- id
- name
- etc

conversation_user (pivot)
- user_id
- conversation id

我的模型 Conversation belongsToMany Users 和 User belongsToMany Conversations。

添加对话并将用户附加到数据透视表工作正常,但我找不到检查两个用户之间是否存在对话的干净方法。

感谢您的帮助。

【问题讨论】:

    标签: php laravel laravel-5 eloquent


    【解决方案1】:

    试试下面的查询,看看是否对你有帮助:

    Conversation::whereHas('users', function($query) use ($userIds) {
        $query->whereIn('id', $userIds);
    })->exists();
    

    【讨论】:

      【解决方案2】:

      使用@ruffles 回答并稍作改动:

      $hasConversation = Conversation::whereHas('users', function($query) use ($userIds) {
          $query->whereIn('id', $userIds);
      })->count() === 2;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-06
        • 2016-09-26
        • 2017-07-13
        • 2018-04-04
        • 1970-01-01
        • 2017-01-02
        • 1970-01-01
        相关资源
        最近更新 更多