美文网首页
Laravel下的数据库查询

Laravel下的数据库查询

作者: TwT_Zhangkai | 来源:发表于2017-11-02 18:39 被阅读0次

嵌套where子句

在进行数据库查询操作时,有时候数据库的操作并不是简单的一两个where子句,而是更加复杂的条件,这个时候就要用到嵌套where子句。请看下面一段代码:

public static function noneMembersUndergraduateNotYear($academy_id){
    $res = self::where('partybranch_id', '<', 1)
        ->where('academy_id', $academy_id) //条件1
        ->where('main_status', 0) //条件2
        ->where('sno', 'like', "30%") //条件3
        ->orWhere('sno', 'like', "40%") //条件4
        ->get()->all();
    return array_map(function ($studentInfo){
        return Resources::StudentInfo($studentInfo);
    }, $res);
}

这段代码的本意是取出满足(条件1&&条件2&&(条件3||条件4))的数据,但实际上程序是分不清条件4的orWhere是相对于条件1、条件2、条件3中的哪一个的,这个时候我们就要把条件3和条件4用一个闭包合在一起,代码修改如下:

public static function noneMembersUndergraduateNotYear($academy_id){
    $res = self::where('partybranch_id', '<', 1)
        ->where('academy_id', $academy_id)
        ->where('main_status', 0)
        ->where(function ($query){
            $query->where('sno', 'like', "30%")
                ->orWhere('sno', 'like', "40%");
        })
        ->get()->all();
    return array_map(function ($studentInfo){
        return Resources::StudentInfo($studentInfo);
    }, $res);
}

如果闭包函数里需要用到外层函数的参数,就需要在闭包函数里use这个参数,不use直接使用外层函数的参数是会报错的。例如上面代码中的noneMembersUndergraduateNotYear函数如果多一个参数$shooch_year,且闭包函数需要调用这个参数,则代码如下:

public static function noneMembersUndergraduate($academy_id, $school_year){
    $res = self::where('partybranch_id', '<', 1)
        ->where('academy_id', $academy_id)
        ->where('main_status', 0)
        ->where(function ($query) use($school_year){
            $query->where('sno', 'like', "3_$school_year%")
                ->orWhere('sno', 'like', "4_$school_year%");
        })
        ->get()->all();
    return array_map(function ($studentInfo){
        return Resources::StudentInfo($studentInfo);
    }, $res);
}

like语句--模糊查询

看下面的一段代码

        ->where('sno', 'like', "30%") //条件3
        ->orWhere('sno', 'like', "40%") //条件4

这段代码表示查询学号‘30’和‘40’开头的,'%'为通配符,替代一个或多个字符,除此之外,还有以下通配符:

通配符 描述
% 替代一个或多个字符
_ 替代一个字符
[charlist] 字符列中的任何单一字符
[^charlist] 或者 [!charlist] 不在字符列中的任何单一字符

如果like之后的要传参数,参数一定要包含在" "中,参数在' '中会报错

        ->where(function ($query) use($school_year){
            $query->where('sno', 'like', "3_$school_year%")
                ->orWhere('sno', 'like', "4_$school_year%");
        })

相关文章

网友评论

      本文标题:Laravel下的数据库查询

      本文链接:https://www.haomeiwen.com/subject/qxdapxtx.html