2

I want to write this query in eloquent using raw queries :

INSERT INTO table SELECT * FROM other_table WHERE other_table_id IN (1,2,3)

I've tried writing it like this :

use Illuminate\Database\Capsule\Manager as DB;
$insert_db = DB::select("SELECT products_id FROM products WHERE products_id IN (?)", [[265792,265787,265743]])

But this is giving me an empty array as a result.

What is the correct way of writing this using the capsule manager? (I absolutely need to do it using DB::select)

This question is asking the same thing, back in 2013. Back then it was not possible. So did that change today? Can we use WHERE IN (?) in the latest versions of eloquent? Knowing that I NEED to use ? for security, and not concatenate the string or it would be meaningless to use PDO at all.

EDIT :

The question is more about dynamic values. I can't use :

DB::select("SELECT products_id FROM products WHERE products_id IN (?, ?, ?)", [265792,265787,265743]);

Because the array [265792,265787,265743] is being built elsewhere. So imagine the following code

foreach($test as $k => $v) {
    $arr[] = $v['something']
}

DB::select("SELECT products_id FROM products WHERE products_id IN (?)", [[$arr]]);
Alexandre Elshobokshy
  • 10,720
  • 6
  • 27
  • 57

2 Answers2

2

You need a placeholder for every binding:

$placeholders = implode(', ', array_fill(0, count($arr), '?'));
DB::select("SELECT products_id FROM products WHERE products_id IN ($placeholders)", [$arr]);

In Laravel/Eloquent 5.7.17+, you can use insertUsing():

DB::table('table')->insertUsing(['foo', 'bar'], function ($query) use ($arr) {
    $query->from('other_table')
        ->whereIn('other_table_id', $arr);
});

Note that the method requires you to specify the column names (['foo', 'bar']).

Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109
2

A cleaner approach to generate the ?, placeholders is to use str_repeat:

$in = str_repeat('?,', count($arr) - 1) . '?';

Edit #1

To handle instances where you have zero items in your array, I came up with the following function:

function in($arr)
{
  return count($arr) > 0 ? str_repeat('?,', count($arr) - 1) . '?' : false;
}

Live Example

Repl

Script47
  • 14,230
  • 4
  • 45
  • 66
  • This won't work in the case of if `count($arr)` is equal to zero. As it'll always give 1 `?` and when `count($arr) == 0` we'd want no exclamtion marks. – Alexandre Elshobokshy Mar 18 '19 at 14:48
  • And if there are not results, in mysql, false won't return an error? – Alexandre Elshobokshy Mar 18 '19 at 15:16
  • I guess, you'd first validate your array, if values exists, run the where in, otherwise don't and give an error message as correct values have not been passed (or something like that). – Script47 Mar 18 '19 at 15:17
  • @GiveMeFreedomOrGiveMeFire use the pre-edit code and validate before the query to check if the array has values. – Script47 Mar 18 '19 at 15:19