mysql – 在Laravel中查询串联

我有以下方法:

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'");
        }

如您所见,$query是使用数组中的元素构建的.

在Laravel中构建和运行查询时,我在“第12行”附近收到语法错误.

将查询从错误消息复制到phpmyadmin时,我得到了我需要的信息.

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

最佳答案 您在IN语句的末尾缺少右括号

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. = ")";
点赞