簡體   English   中英

在 laravel 中的 where 條件下使用數組

[英]using array in where condition in laravel

我正在使用 laravel 6.我想使用我的日程安排中的時間限制。 限制變量是包含多個字符串數據的數組。

$bus = BusSchedule::where([
           ['datetime', '>=', $start_datetime],
           ['datetime', '<=', $end_datetime]
     ])
    ->get()
    ->pluck('course_id')
    ->toArray();

在 start_datetime 和 end_datetime 變量中,我有多個日期時間,例如 ['2020-12-12 16:05:00','2020-12-11 13:05:00']

它應該是。 start_datetime 和 end_datetime 是用戶輸入的動態數組

$bus = BusSchedule::where([
           ['datetime', '>=', ['2020-12-12 16:05:00' ,'2020-12-11 13:05:00']],
           ['datetime', '<=', ['2020-12-12 18:05:00' ,'2020-12-11 15:05:00']]
     ])
    ->get()
    ->pluck('course_id')
    ->toArray();

但我得到數組第一個索引的值,其他的不工作

我認為對於日期和“>=”或“<=”,您可以只使用輸入數組的最小值/最大值。 因為您不關心兩者之間的精確值,您只需要一個范圍,尤其是如果您想要列出用戶選擇日期之間的所有結果。

所以你的代碼會是這樣的:

$bus = BusSchedule::whereBetween('datetime', [
       min(Carbon::create('2020-12-12 18:05:00') ,Carbon::create('2020-12-11 15:05:00')),
       max(Carbon::create('2020-12-12 16:05:00') ,Carbon::create('2020-12-11 13:05:00'))
 ])
->get()
->pluck('course_id')
->toArray();

如果你只想要匹配所有日期的結果,就好像你對每個值做多個 wheres,你可以在 max(start_dates) 和 min(end_dates) 之間使用

但是,如果您想要位於那些選定日期之間的任何結果,您可以在 min(start_dates) 和 max(end_dates) 之間使用。

這將包括所有選項

當你想要精確的值時,你可以使用whereIn

有關 laravel 中選擇的更多信息: https://laravel.com/docs/6.x/queries#selects

有關 Carbon 中 min 的更多信息: https://carbon.nesbot.com/docs/#api-comparison

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM