douzhi3667 2018-04-29 08:08
浏览 290
已采纳

PHP Laravel:理解这个闭包

I have this snippet from the Laravel documentation:

DB::table('users')
            ->whereExists(function ($query) {
                $query->select(DB::raw(1))
                      ->from('orders')
                      ->whereRaw('orders.user_id = users.id');
            })
            ->get();

I need to understand two things.

  1. Where does the $query parameter to the closure come from? I suspect that there is something happening under the hood that I don't understand. The function takes 1 parameter, the $query, but where does it come from, how does this function know what is in this parameter, what is passed into the function?
  2. It appears that this closure doesn't return a value, there is no return statement. So how does the whereExists method know the return value of the closure?
  • 写回答

1条回答 默认 最新

  • doushi3715 2018-04-29 08:22
    关注

    Refer to the source: https://github.com/laravel/framework/blob/987a21f39f203c76665f6014cbef10451689fbdd/src/Illuminate/Database/Query/Builder.php#L1333

    As you can see the closure is treated like a callback.

    So whereExists passes $query to it. $query is an instance of self (Builder) class, so the code in the closure is just updating the object.

    /**
     * Add an exists clause to the query.
     *
     * @param  \Closure $callback
     * @param  string   $boolean
     * @param  bool     $not
     * @return $this
     */
    public function whereExists(Closure $callback, $boolean = 'and', $not = false)
    {
        $query = $this->forSubQuery();
        // Similar to the sub-select clause, we will create a new query instance so
        // the developer may cleanly specify the entire exists query and we will
        // compile the whole thing in the grammar and insert it into the SQL.
        call_user_func($callback, $query);
        return $this->addWhereExistsQuery($query, $boolean, $not);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Attributeerror:super object has no attribute '__sklearn_tags__'_'
  • ¥15 逆置单链表输出不完整
  • ¥15 宇视vms-B200-A16@R启动不了,如下图所示,在软件工具搜不到,如何解决?(操作系统-linux)
  • ¥500 寻找一名电子工程师完成pcb主板设计(拒绝AI生成式答案)
  • ¥15 关于#mysql#的问题:UNION ALL(相关搜索:sql语句)
  • ¥15 matlab二位可视化能否针对不同数值范围分开分级?
  • ¥15 已经创建了模拟器但是不能用来运行app 怎么办😭自己搞两天了
  • ¥15 关于#极限编程#的问题,请各位专家解答!
  • ¥20 win11账户锁定时间设为0无法登录
  • ¥45 C#学生成绩管理系统