我正在使用laravel,我在一个模型中使用了这个方法。
当我在PhpMyAdmin或MySQL控制台中运行查询时,我得到了预期的结果。
在Laravel中运行时,我总是得到同一行,甚至不满足查询中的“where”语句。使用ORDER BY RAND()
public static function getPotentialMatch($id, $genderId = NULL)
{
$query = "SELECT
student.id AS id,
(SELECT COUNT(*) FROM matches AS m WHERE m.local_student_id = student.id) AS matches
FROM
users AS user
JOIN students AS student
ON user.id = student.user_id
LEFT OUTER JOIN languages_student AS ls
ON student.id = ls.student_id
LEFT OUTER JOIN languages AS language
ON ls.language_id = language.id
LEFT OUTER JOIN courses AS course
ON student.course_id = course.id
WHERE ls.language_id IN
(
SELECT ls.language_id AS languageId
FROM languages_student AS ls
JOIN students AS student1
ON ls.student_id = student1.id
JOIN users AS user1
ON student1.user_id = user1.id
WHERE student1.id = " . $id . "
)
AND student.course_id IN
(
SELECT courseR.id AS affinityId
FROM courses AS course
JOIN course_affinities
ON course.id = course_affinities.course1_id
OR course.id = course_affinities.course2_id
JOIN courses AS courseR
ON (courseR.id = course_affinities.course1_id
AND courseR.id <> course.id)
OR (courseR.id = course_affinities.course2_id
AND courseR.id <> course.id)
WHERE course.id IN
(
SELECT student.course_id
FROM students AS student
WHERE student.id = " . $id . "
)
)
AND student.incoming = 0
AND student.active = 1
AND (
SELECT COUNT(*)
FROM matches AS m
WHERE m.local_student_id = student.id
) < 3
";
if ($genderId != NULL) {
$query .= " AND student.gender_id = " . $genderId;
}
$query .= " ORDER BY (SELECT COUNT(*) FROM matches AS m WHERE m.local_student_id = student.id)
LIMIT 1";
return DB::select(DB::raw($query));
}
有什么想法吗?