Concatenating queries in Laravel

I have the following methods:

public function getSpecialIncomings()
        {
            $countries = $this->getSpecialCountries();

            $query =    "SELECT id          AS studentId,
                                gender_id   AS genderId
                        FROM    students    AS student
                        WHERE student.incoming = 1
                        AND student.country_id IN
                        (
                        SELECT id FROM countries AS country";

            if(count($countries) > 0)
            {
                $query .= " WHERE country.name = " . $countries[0] . " \r\n ";

                for($i = 1; $i < count($countries); $i++)
                {
                $query .= " OR country.name = " . $countries[$i] . " \r\n ";
                }
            }

            return DB::select(DB::raw($query));
        }

    public function getSpecialCountries()
        {
            return array("'China'", "'Korea'", "'Japan'", "'Jordan'", "'Taiwan'", "'Malaysia'");
        }

As you can see, the $ query is built with elements in the array.

When I create and execute a query in Laravel, I get a syntax error near " at line 12.

When copying a request from an error message in phpmyadmin, I get the necessary information.

    SELECT  id        AS studentId,
            gender_id AS genderId
    FROM students AS student
    WHERE student.incoming = 1
    AND student.country_id IN
    (
        SELECT id FROM countries AS country 
        WHERE country.name = 'China' 
        OR country.name = 'Korea' 
        OR country.name = 'Japan' 
        OR country.name = 'Jordan' 
        OR country.name = 'Taiwan' 
        OR country.name = 'Malaysia'
    )
+4
source share
2 answers

You are missing the closing parenthesis at the end of your IN statement

if(count($countries) > 0)
{
   $query .= " WHERE country.name = " . $countries[0] . "\r\n";

   for($i = 1; $i < count($countries); $i++)
   {
     $query .= " OR country.name = " . $countries[$i] . "\r\n";
   }
}

$query. = ")";
+1
source

Here is an eloquent way to make a request:

public function getSpecialIncomings()
{
    $countries = $this->getSpecialCountries();
    //Init query builder
    $query = \DB::table('students')
            ->select('id as studentId','gender_id as genderId')
            ->where('incoming','=',1)

    if(count($countries)) {
        //Where in list of countries
        $query->whereExists(function($query) use ($countries){
            $query->select('id')
            ->from('countries')
            ->whereIn('name',$countries)
        });
    }

    return $query->get();    
}   
+1
source

Source: https://habr.com/ru/post/1628914/


All Articles