【问题标题】:how to pass array in whereMonth method of laravel eloquent如何在laravel eloquent的whereMonth方法中传递数组
【发布时间】:2021-05-13 01:38:41
【问题描述】:

我必须为 whereMonth.. 传递一个数组。

$months = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];

$user_date = UserDetails::where('userId', '=', $id)
    ->whereMonth('created_at', $months[1])
    ->whereYear('created_at', date('Y'))
    ->pluck('date');

【问题讨论】:

  • ? whereMontth 表示你想要的只有 1 个月?
  • whereMonth('created_at', $months) 我想要这个,所以它可以检查所有月份。不仅适用于 $months[0] = '01'
  • 如果你想检查所有月份意味着只使用whereYear(),如果你想要两个月之间,那么你需要用户whereBetween()
  • @KamleshPaul 但我想要特定月份的记录,我检查了 whereYear(),它提供了所有记录。

标签: mysql laravel eloquent where-in


【解决方案1】:

为了避免原始表达式,您可以使用 虚拟列

1.在created_at 列之后将此添加到您的迁移中

$table->char('created_at_month',3)->virtualAs('DATE_FORMAT(created_at,"%m")');

运行您的迁移

现在您可以运行以下查询来获取在特定月份创建的记录

$months = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];

$user_date = UserDetails::where('userId', '=', $id)
    ->whereIn('created_at_month', $months)
    ->whereYear('created_at', date('Y'))
    ->pluck('date');

如果您想了解更多信息,请查看以下链接

  1. https://laravel.com/docs/8.x/migrations#column-modifiers
  2. https://www.w3schools.com/sql/func_mysql_date_format.asp

【讨论】:

  • 这将使整个表格过于复杂,仅针对单个过滤器,我认为除非有引入此类更改的有效要求,否则不应向用户建议,@Jignesh Joisar 发布的解决方案远比这个好
  • 我已经明确提到,如果你想避免原始表达式并提高性能,他可以使用我的解决方案@M Khalid Junaid
【解决方案2】:

这里需要使用whereRaw方法

$months = [1,2,3,4,5,6,7,8,9,10,11,12];

$user_date = UserDetails::selectRaw("*,MONTH(created_at) as month_at")
    ->where('userId', '=', $id)
    ->whereRaw('MONTH(created_at) in ('.implode(',',$months).')')
    ->whereYear('created_at', date('Y'))
    ->pluck('date');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    相关资源
    最近更新 更多