Laravel Eloquent 如何在操作符之间使用

2021-12-26 00:00:00 sql php laravel laravel-4 eloquent

我试图在 Eloquent 和 Laravel 中找到一种优雅的方式来表达

I am trying to find an elegant way in Eloquent and Laravel to say

select * from UserTable where Age between X and Y

Eloquent 中是否有 between 运算符(我找不到).

Is there a between operator in Eloquent (I can't find it).

到目前为止我得到的最接近的是像这样链接我的查询

The closest i have gotten so far is chainging my query like this

$query->where(age, '>=', $ageFrom)
      ->where(age, '<=', $ageTo);

我也遇到过 whereRaw 似乎有效

I also came across whereRaw that seems to work

$query->whereRaw('age BETWEEN ' . $ageFrom . ' AND ' . $ageTo . '');

是否有处理范围的实际 Eloquent 方式(非原始)?

Is there an actual Eloquent way (not raw) that deals with ranges?

推荐答案

$query->whereBetween('age', [$ageFrom, $ageTo]);

看这里:http://laravel.com/docs/4.2/queries#selects

仍然适用于 Laravel 5:https://laravel.com/docs/5.8/queries#where-clauses

Still holds true for Laravel 5: https://laravel.com/docs/5.8/queries#where-clauses

相关文章