其中orWhere Laravel 5.5逻辑DB问题

时间:2017-12-05 10:10:17

标签: database laravel where helper

我在痛苦中

这是我的帮手

$friend_querry = Friend::where([
        'user_id' => Auth::id(),
        'friend_id' => $friend_id,
        ])->orWhere([
        'user_id' => $friend_id,
        'friend_id' => Auth::id(),
        ])->first();




        $friendship = new stdClass();
        $friendship->exist = false;
        $friendship->accepted = false;

        if (! is_null($friend_querry))
        {
        $friendship->accepted = $friend_querry->accepted;
        $friendship->exist = true;
    }
        var_dump($friendship->exist);
        exit;
        return $friendship;

enter image description here

当我记录为'user_id'=> auth :: id() - 一切都很好但是当我被记录为'friend_id'时,请求总是var_dump返回我的确...这是第三天我找不到解决方案。 DB的照片包含在帖子中。

3 个答案:

答案 0 :(得分:0)

试试这样:

$friend_querry = Friend::where([
                                'user_id' => Auth::id(),
                                'friend_id' => $friend_id,
                                ])
                        ->orWhere(function ($query) use($friend_id) {
                                    $query->where([
                                            'user_id' => $friend_id,
                                            'friend_id' => Auth::id(),
                                            ]);
                                })
                        ->first();

答案 1 :(得分:0)

谢谢你, 只需要很少的语法错误

->orWhere(function ($query) {

但有一个问题 - 未定义的变量:friend_id

就像这样

function friendship($friend_id){
friend_querry = Friend::where([
        'user_id' => Auth::id(),
        'friend_id' => $friend_id,
        ])->orWhere(function ($query) {
                                $query->where([
                                        'user_id' => $friend_id,
                                        'friend_id' => Auth::id(),
                                        ]);
                            })
                    ->first();
... }

答案 2 :(得分:0)

当你想" group"您的where条款,您应该传递closure,然后在其中执行您的条件。比如说,您希望查询看起来像这样

  

SELECT * FROM friends WHERE(user_id =?AND friend_id =?)OR(user_id =?AND friend_id =?)LIMIT 1

然后,这个雄辩的版本将是

$friend_query = Friend::where(function ($query) use ($friend_id) {
    $query->where('user_id', Auth::id())
        ->where('friend_id', $friend_id);
})->orWhere(function ($query) use ($friend_id) {
    $query->where('friend_id', Auth::id())
        ->where('user_id', $friend_id);
})->first();