Laravel模型里面的when()用法

Laravel 5.5 里面的when用法:

// \DB::enableQueryLog();
$data = StudentClassHour::where('student_info_id', $student_info_id)
    ->where('status', 1)
    ->when($type == 1, function ($query) {
        $query->whereIn('hour_type', [1, 2, 3, 4, 5]);
    })
    ->when($type == 2, function ($query) {
        $query->whereIn('hour_type', [6, 7, 8]);
    })
    ->get();
// dd(\DB::getQueryLog());

源代码路径:
D:\phpStudy\WWW\BCCKidV1.0\vendor\laravel\framework\src\Illuminate\Database\Concerns\BuildsQueries.php

    public function when($value, $callback, $default = null)
    {
        if ($value) {
            return $callback($this, $value) ?: $this;
        } elseif ($default) {
            return $default($this, $value) ?: $this;
        }

        return $this;
    }

不难看出,when会判断第一个参数的真与假,如果是真,则执行第一个callback,如果是假,则执行默认的方法,我的那段代码就只设置了真的时候需要执行的代码,因为条件有三种,不只有两种。这样的话可以使代码易读性更好,当然也可以拆分子句,但是when这个用法相对更赞。
另外,在集合collection中,也有这个方法,用法一样的。源文件位置:
D:\phpStudy\WWW\BCCKidV1.0\vendor\laravel\framework\src\Illuminate\Support\Collection.php

laravel 5.5 支持的 operators :

D:\phpStudy\WWW\xxx\vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php

public $operators = [
        '=', '<', '>', '<=', '>=', '<>', '!=', '<=>',
        'like', 'like binary', 'not like', 'ilike',
        '&', '|', '^', '<<', '>>',
        'rlike', 'regexp', 'not regexp',
        '~', '~*', '!~', '!~*', 'similar to',
        'not similar to', 'not ilike', '~~*', '!~~*',
];

参考:
https://www.cnblogs.com/geaozhang/p/6733737.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SHUIPING_YANG

你的鼓励是我创作的最大动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值