Sebastian M
Sebastian M

Reputation: 491

Query concatenation in Laravel

I have 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 the elements in the array.

When building and running the query in Laravel, I get an syntax error near " at line 12.

When copying the query from the error message to phpmyadmin, I get the info I need.

    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'
    )

Upvotes: 4

Views: 188

Answers (2)

Mysteryos
Mysteryos

Reputation: 5791

Here's the eloquent way to do the query:

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

Upvotes: 1

James Joyce Alano
James Joyce Alano

Reputation: 703

You are missing a 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. = ")";

Upvotes: 1

Related Questions