Laravel Eloquent - 多参数查询
Laravel Eloquent - Query with multiples parameters
我是 Laravel 框架的新手,可能需要您的一些帮助。
有人可以帮我把这个请求转换成 Eloquent 吗?
SELECT * FROM `non_working_days` WHERE YEAR(date) = "2021" AND (country = "Paris" OR country = "Madrid")
目前我已经设法找到了解决方案,但我的查询运行与参数的数量一样多。
foreach ($calendar as $code) {
array_push(
$data,
Model::query()
->whereYear('date', '=', $year)
->where('country', $code)
->get()
);
}
归结为:
SELECT * FROM `non_working_days` WHERE YEAR(date) = "2021" AND country = "Paris"
SELECT * FROM `non_working_days` WHERE YEAR(date) = "2021" AND country = "Madrid"
所以我认为知道我可能会有更多参数不是很有效。
谢谢
您可以使用whereIn方法:
$countries = ['Paris', 'Madrid']; // or use $calendar instead if it's an array
$data = Model::query()
->whereYear('date', '=', $year)
->whereIn('country', $countries)
->get();
这应该给你这样的查询:
SELECT * FROM `non_working_days` WHERE YEAR(`date`) = "2021" AND `country` IN ("Paris", "Madrid");
你可以通过使用 where in 来做到这一点,你不需要为此做循环,就像这样:-
Model::query()
->whereYear('date', '=', $year)
->whereIn('country', $calendar)
->get()
你可以做到,
Model::query()
->whereYear('date', '=', $year)
->where( function( $whereQry ) use( $country_1, $country_2 ) {
$whereQry->orWhere( 'country', $country_1 );
$whereQry->orWhere( 'country', $country_2 );
})
->get();
它会转换成您所需要的,
SELECT * FROM `non_working_days` WHERE YEAR(date) = "2021" AND (country = "Paris" OR country = "Madrid")
我是 Laravel 框架的新手,可能需要您的一些帮助。
有人可以帮我把这个请求转换成 Eloquent 吗?
SELECT * FROM `non_working_days` WHERE YEAR(date) = "2021" AND (country = "Paris" OR country = "Madrid")
目前我已经设法找到了解决方案,但我的查询运行与参数的数量一样多。
foreach ($calendar as $code) {
array_push(
$data,
Model::query()
->whereYear('date', '=', $year)
->where('country', $code)
->get()
);
}
归结为:
SELECT * FROM `non_working_days` WHERE YEAR(date) = "2021" AND country = "Paris"
SELECT * FROM `non_working_days` WHERE YEAR(date) = "2021" AND country = "Madrid"
所以我认为知道我可能会有更多参数不是很有效。
谢谢
您可以使用whereIn方法:
$countries = ['Paris', 'Madrid']; // or use $calendar instead if it's an array
$data = Model::query()
->whereYear('date', '=', $year)
->whereIn('country', $countries)
->get();
这应该给你这样的查询:
SELECT * FROM `non_working_days` WHERE YEAR(`date`) = "2021" AND `country` IN ("Paris", "Madrid");
你可以通过使用 where in 来做到这一点,你不需要为此做循环,就像这样:-
Model::query()
->whereYear('date', '=', $year)
->whereIn('country', $calendar)
->get()
你可以做到,
Model::query()
->whereYear('date', '=', $year)
->where( function( $whereQry ) use( $country_1, $country_2 ) {
$whereQry->orWhere( 'country', $country_1 );
$whereQry->orWhere( 'country', $country_2 );
})
->get();
它会转换成您所需要的,
SELECT * FROM `non_working_days` WHERE YEAR(date) = "2021" AND (country = "Paris" OR country = "Madrid")