【问题标题】:Laravel Eloquent - Query with multiples parametersLaravel Eloquent - 多参数查询
【发布时间】:2021-05-12 22:59:03
【问题描述】:

我是 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"

所以我认为知道我可能会有更多参数并不是很有效。

谢谢

【问题讨论】:

    标签: php laravel eloquent eloquent-relationship


    【解决方案1】:

    您可以使用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");
    

    【讨论】:

      【解决方案2】:

      你可以通过使用 where in 来做到这一点,你不需要为此创建循环,就像这样:-

      Model::query()
        ->whereYear('date', '=', $year)
        ->whereIn('country', $calendar)
        ->get()
      

      【讨论】:

      • 但是 $countries 数组应该是这样的:- ['Paris', 'Madrid']
      【解决方案3】:

      你可以做到的,通过

      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")
      

      【讨论】:

      • 只有当我只有两个参数时,您的建议才对我来说是正确的。只要我有几个参数,代码就会非常复杂。我认为最好使用 OR key IN ('key1', 'key2')。感谢您的帮助。
      • whereIn 如果要将多值匹配到单个列,则最好。但这将帮助您在 SQL 查询中实际需要 OR 操作的地方。所以这是供您将来使用的。
      猜你喜欢
      • 2021-02-11
      • 1970-01-01
      • 2017-07-30
      • 1970-01-01
      • 1970-01-01
      • 2017-10-22
      • 2014-10-31
      • 2014-10-25
      • 2019-07-21
      相关资源
      最近更新 更多