Skip to content
Advertisement

Laravel 9 – implode() and whereIn

Hello i’m using query builder in my laravel app. I’m trying to use the implode() method from query builder.

    $edi_data_mysql = DB::table('orders_grid')
                    ->select('id')
                    ->where('stato_ordine', 1)
                    ->get()
                    ->implode('id', "', '"); 
                    
    
    dump($edi_data_mysql); // returns "2, 3, 5"

   $jde_data = DB::connection('oracle')->table('table')
                   ->select('col1', 'col2', 'col3', 'col4')
                   ->where('col5', DB::raw("TRIM('Y')"))
                   ->whereIn('oracle_id', $edi_data_mysql)
                   ->get();

So for example i expect a string composed from : ‘ 2,3,4… ‘ I have to use this string in next query where i use the raw query IN (‘value’, ‘value’)

I’m trying to wrap those IDs in to single quotes like ” ‘2’, ‘3’, ‘4’ ” but without results.

I know that i could use later the whereIn() method that accepts an array as second param, but the problem remains always about the ID wrap, because on the db that value is a string.

Which way should i go for? I need to avoid the loop*

Advertisement

Answer

commonly whereIn method accept array as a second parameter. but you are passing string. I think this should solve your problem.

$edi_data_mysql = DB::table('orders_grid')
                ->select('id')
                ->where('stato_ordine', 1)
                ->pluck('id')
                ->toArray(); 
                

dump($edi_data_mysql); // returns **[2, 3, 5]**

$jde_data = DB::connection('oracle')->table('table')
               ->select('col1', 'col2', 'col3', 'col4')
               ->where('col5', DB::raw("TRIM('Y')"))
               ->whereIn('oracle_id', $edi_data_mysql)
               ->get();

By this way you can avoid loop. No matter it is string or integer, it should work for both.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement