【问题标题】:Laravel eloquent SQL query with OR and AND with where clauseLaravel 雄辩的 SQL 查询与 OR 和 AND 与 where 子句
【发布时间】:2014-08-23 17:39:07
【问题描述】:

我知道sql AND 可以通过连续的where 子句来实现。和 OR 与 where(条件,'OR')。 我想从 sendTo = editor_id AND sentFrom= currentUser_id OR where sentTo = currentUser_id AND sentFrom = editor_id 的消息表中选择所有消息。 我有这个查询,我试图通过它来获得结果,

    $this->data['messages'] = Message::where(function ($query) use($uId) {
        $query->where('sentTo', '=', $this->data['currentUser']->id)
            ->orWhere('sentFrom', '=', $uId);
            })
    ->where(function ($query) use($uId){
             $query->where('sentTo', '=', $uId)
                     ->orWhere('sentFrom', '=', $this->data['currentUser']->id);
            })
    ->get();

我该怎么做?请指教。

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    我有点困惑,因为您没有提供括号来知道您想要哪个运算符优先级。

    假设你想要WHERE (editor_id=$editorId AND sentFrom=$currentUserId) OR (sentTo=$currentUserId AND sentFrom=$editorId),那么最新版本的 Laravel 允许你这样做:

        Message::where(['editor_id' => $editorId, 'sentFrom' => $currentUserId])
        ->orWhere(['sentTo' => $currentUserId, 'sentFrom' => $editorId])->get();
    

    无需使用闭包。

    【讨论】:

    • 哇!我不知道可以这样做。正是我想要的。谢谢
    • 这很棒。我自己在 Laravel 4.2 中使用过类似的东西
    • 一年多过去了,这仍然是互联网上最好的答案。适用于 5.1
    【解决方案2】:

    试试这个

    $this->data['messages'] = Message::where(function ($query) use($uId) {
        $query->where('sentTo', '=', $this->data['currentUser']->id)
              ->where('sentFrom', '=', $uId);
    })-> orWhere(function ($query) use($uId){
        $query->where('sentTo', '=', $uId)
              ->Where('sentFrom', '=', $this->data['currentUser']->id);
    })->get();
    

    【讨论】:

    • 感谢您的努力,但我正在从控制器中的 _construct() 函数中获取 currentUser 对象。所以它无处不在。但是,当您将对象作为 id 传递时,您的解决方案将不起作用。此外,如果 currentUser->id 不在范围内,我会得到一个未定义的错误,我没有得到。我得到的结果是空的。谢谢
    • 我认为问题是由 $this 引起的,请确保在执行请求之前您拥有 $this->data['currentUser']->id。
    • 我成功了,$this->data['messages'] = Message::where(function ($query) use($uId) { $query->where('sentTo', '=', $this->data['currentUser']->id) ->Where('sentFrom', '=', $uId); }) ->orwhere(function ($query) use($uId){ $query->where('sentTo', '=', $uId) ->Where('sentFrom', '=', $this->data['currentUser']->id); }) ->get();感谢您的努力@Issam
    猜你喜欢
    • 1970-01-01
    • 2016-07-05
    • 2018-05-19
    • 1970-01-01
    • 2017-01-30
    • 2021-07-04
    • 2021-02-13
    • 2014-12-02
    • 1970-01-01
    相关资源
    最近更新 更多