php - Laravel-友谊

标签 php mysql laravel laravel-5

我正在尝试在 laravel 5 中建立一个友谊系统,但我被卡住了。 我有一个 friends_user 表,如下所示:

  • 编号
  • 用户编号
  • friend_id
  • 状态

重点是,我转到一个用户页面,我想看看我和这个用户的关系如何,4 个解决方案:

  • 我们是 friend
  • 我们不是
  • 他还没有接受请求
  • 我要确认与否。

我想创建一个方法来检查一个用户是否是另一个用户的 friend ,很简单。 我有一个“状态”列,它是一个 bool 值(0 表示待处理,1 表示 friend ) 对我来说,完美的解决方案是能够用一种方法检查是否:

  • 用户是 friend ,所以要么 ('user_id', Auth::user()->id)->and ('friend_id', $friend->id) 要么相反 ('user_id', $friend->id)->and ('friend_id', Auth::user()->id), 它必须检查 2 个感官
  • 我发送了请求,必须等待他的答复
  • 我收到了请求并且必须接受它。
  • 我们不是 friend ,所以我可以加他。

所以如果你能告诉我我哪里错了,这是我的逻辑(只是为了检查用户是否是 friend ):User.php

    public function isFriend($slug)
{
    // Get both user
    $user = Auth::user();
    $receiver = User::where('slug', $slug)->first();
    // get list of friends (so who have status = 1)
    $result = Friends::where('status', 1);
    // Get users where user id is equal to connected
    $result = $result->where('user_id', $user->id)->where('friend_id', $receiver->id);
    $result = $result->orWhere('user_id', $receiver->id)->where('friend_id', $user->id);
    $result = $result->get();
    if(count($result) == 0)
        return false;
    return true;
}

在我进行这些检查之后。

这非常有效,但前提是我(当前用户)已发送请求,但如果它是相反的,即使状态为 0,它也会返回用户。我认为我的 $result 删除其他的不是吗?那有什么办法呢?

我希望它很清楚,如果你能告诉我如何以干净的方式做到这一点,那就太好了。

最佳答案

这是一个常见的错误。当心你的“orWhere”条款。

public function isFriend($slug)
{
    // Get both user
    $user = Auth::user();
    $receiver = User::where('slug', $slug)->first();
    // get list of friends (so who have status = 1)

    $result = Friends::where('status',1)->where(function($query) use ($receiver,$user)
    {
        $query->where([
            'user_id'   => $user->id,
            'friend_id' => $receiver_id
        ])->orWhere([
            'user_id'   => $receiver->id,
            'friend_id' => $user->id
        ]);

    })->get();

    return ! $result->isEmpty();
}

关于php - Laravel-友谊,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29824713/

相关文章:

php - Laravel 验证规则 : required_without

适用于 Windows 的 PHP 编译器

mysql - 如何使用观察者将新列添加到订单网格?

mysql - Laravel Eloquent ORM WHERE IN(子查询)

MySQL INTO OUTFILE 错误?

mysql - 使用 sequelize,如何将 OR 运算符与 where 条件一起使用?

events - Laravel 事件处理程序和监听器

php - 超过两行时包含字符串计数的 MySQL 过滤器

PHP mysql 排序行

php - PayPal 智能支付按钮错误 paypal.Buttons 不是函数