How to get all records where column value is equals one of the array elements?

How to get all records where column value is equals one of the array elements?

vivalazvivalaz Posts: 10Questions: 6Answers: 0
edited February 2018 in Free community support

I have an array $deals_arr = [19300, 19301, 19305]. How to find all records where id_deal is equals one of the array elements? Help, please!

$out = Editor::inst( $db, 'deals' )
  ->fields(
    Field::inst( 'id'),
    Field::inst( 'id_deal'),
  )
  ->where(function($q) use($deals_arr) {
    $q->where('id_deal', $deals_arr, '=');
  })
  ->process( $_POST )
  ->json();

This question has accepted answers - jump to:

Answers

  • rf1234rf1234 Posts: 2,983Questions: 87Answers: 421
    edited February 2018 Answer ✓

    You would need to format your array in a way SQL accepts using the IN statement. And that is

    where id_deal IN (19300, 19301, 19305)
    
    $sql_arr = '( ';
    for ($i=0; $i < count($deals_arr); $i++) {
       if ($i === 0) {
           $sql_arr = $sql_arr . $deals_arr[$i];
       } else {
           $sql_arr = $sql_arr .  ', ' . $deals_arr[$i];
       }
    }
    $sql_arr = $sql_arr . ' )';
    
    
    $out = Editor::inst( $db, 'deals' )
      ->fields(
        Field::inst( 'id'),
        Field::inst( 'id_deal'),
      )
      ->where(function($q) use($deals_arr) {
       $q->where( 'id_deal', $sql_arr, 'IN', false );
      })
      ->process( $_POST )
      ->json();
    

    Didn't test this but should work hopefully. The "false" parameter is necessary in order to avoid Editor escaping the sql_arr variable as a string. This way it should pass this thing into the database as is.

  • rf1234rf1234 Posts: 2,983Questions: 87Answers: 421
    Answer ✓

    forgot to change the use statement ...
    use($sql_arr)

This discussion has been closed.