zoukankan      html  css  js  c++  java
  • Laravel left join携带多个条件

    在laravel中使用leftJoin添加多个条件时,如select a.* from a left join b on a.id = b.pid and b.status = 1这种类似sql,发现框架自身封装的leftJoin不支持多个参数传递(当然可用写原生sql),laravel框架自身封装的leftJoin方法如下:

     public function leftJoin($table, $first, $operator = null, $second = null)
     {
        return $this->join($table, $first, $operator, $second, 'left');
     }

     浏览下 vendorlaravelframeworksrcIlluminateDatabaseQueryBuilder.php文件,发现join方法可用实现自己想要的left join携带多参数。laravel自身的join方法如下:

    public function join($table, $one, $operator = null, $two = null, $type = 'inner', $where = false)
    {
        // If the first "column" of the join is really a Closure instance the developer
        // is trying to build a join with a complex "on" clause containing more than
        // one condition, so we'll add the join and call a Closure with the query.
        if ($one instanceof Closure) {
            $join = new JoinClause($type, $table);
    
            call_user_func($one, $join);
    
            $this->joins[] = $join;
    
            $this->addBinding($join->bindings, 'join');
        }
    
        // If the column is simply a string, we can assume the join simply has a basic
        // "on" clause with a single condition. So we will just build the join with
        // this simple join clauses attached to it. There is not a join callback.
        else {
            $join = new JoinClause($type, $table);
    
            $this->joins[] = $join->on(
                $one, $operator, $two, 'and', $where
            );
    
            $this->addBinding($join->bindings, 'join');
        }
    
        return $this;
    }

    当左右连接携带多条件时,可以这样写(当join不传left时,默认是inner):

    DB::table('app_a as a')
    ->join('app_b as b',function($join){
        $join->on('a.id','=','b.goodId')
            ->where('b.status','=','SUCCESS')
            ->where('b.type','=','UNLOCK');
    }, null,null,'left')
    ->where('a.id','>',1)
    ->get();
    
    //相当于
    SELECT * FROM app_a as a 
    LEFT JOIN app_b as b on a.id = b.goodId 
    and b.status = 'SUCCESS' and b.type = 'UNLOCK' 
    where a.id > 1;

    参考文章:https://my.oschina.net/u/3403514/blog/1819202/

  • 相关阅读:
    json&display
    postgresql AutoVacuum系统自动清理进程
    postgresql vacuum操作
    C++ 在.h文件中包含头文件和在.cpp文件中包含头文件有什么区别
    ResetEvent、CreateEvent、SetEvent
    《转载》C语言的移位操作符
    《转载》如何使用M6117D看门狗定时器复位系统
    《转载》 Bit,Byte,WORD,DWORD区别和联系
    $.messager.alert
    对一个或多个实体的验证失败
  • 原文地址:https://www.cnblogs.com/itsharehome/p/12293834.html
Copyright © 2011-2022 走看看