使用laravel按年龄过滤

问题描述 投票:0回答:1

各位程序员,早上好。我想询问这个疑问:如何使用参数age来过滤来自我的数据库的数据。在下面的行中,您可以找到我写入日期的代码:

            <div class="form-group">
                <select class="form-control" id="age" name="age">
                    <option selected  disabled>Age</option>
                    <option>All</option>
                    <option value="18-34">18-34</option>
                    <option value="35">35+</option>
                </select>
            </div> 

在以下几行中,您将找到我的业务逻辑中包含的php:

     if($age && $age  != "" && $age != "All") {
            $query->where(function ($q) use($age) {
              $range = explode('-',$age);
              $q->whereBetween('birthday', [$minDate, $maxDate]);
            });
        }

我想对你们所有人表示感谢,并祝愿你们所有人和你们的家人一切顺利。

php laravel
1个回答
1
投票

我假设birthday是约会。然后你可以使用Carbon的subYears()方法:

if (!empty($age) && $age !== 'All') {
    $range = explode('-', $age);

    if (count($range) > 1) {
        $q->whereBetween('birthday', [now()->subYears($range[0]), now()->subYears($range[1])]);
    } else {
        $q->where('birthday', '<', now()->subYears($range[0]))
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.