简体   繁体   中英

using array in where condition in laravel

I am using laravel 6.I want to use time limit from my schedule. the limiting variables are array with multiple string data.

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

in start_datetime and end_datetime variable I have multiple datetime like is ['2020-12-12 16:05:00','2020-12-11 13:05:00']

it should be. start_datetime and end_datetime is dynamic array inputed by user

$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();

but I am getting the value of first index of the array,others are not working

I think with dates and '>=' or '<=' you can just use the min/max of the input array. Because you don't care for exact values in between, you just need a range, especially if you want to list all the results between the user-selected dates.

so your code would be something like:

$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();

if you want only the results that match all dates as if you are doing multiple wheres for every value, you can use between max(start_dates) and min(end_dates)

But if you want any result that lies between those selected dates you use between min(start_dates) and max(end_dates).

That would include all options

When you want exact values you can use whereIn

For more information about selects in laravel: https://laravel.com/docs/6.x/queries#selects

For more information about min in Carbon: https://carbon.nesbot.com/docs/#api-comparison

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM