У меня есть следующая часть более крупного повторяющегося запроса, который работает, когда я не вставляю переменную в DB :: raw.
$tests->join('test_categories', function ($join) use($request) {
$join->on('test_categories.id', '=', DB::raw('(select category_id
from test_category
join test_categories on test_category.category_id = test_categories.id
where test_category.test_id = tests.id
and test_categories.name = ?
limit 1)', ['Cars']
));
});
Но когда SQL выполняется, он исправляет '?' до 4, как в:
and test_categories.name = 4
Вместо того, чтобы быть ожидаемым:
and test_categories.name = 'Cars'
Любая помощь будет оценена.
ОБНОВЛЕНО
Я также пробовал следующее:
$tests->join('test_categories', function ($join) use ($category) {
$join->on('test_categories.id', '=', DB::raw("(select category_id
from test_category
join test_categories on test_category.category_id = test_categories.id
where test_category.test_id = tests.id
and test_categories.name = :category
limit 1)",array('category' => $category)));
});
Но в запросе это просто выводит следующее:
and test_categories.name = :category
Это связано с ошибкой «SQLSTATE [HY093]: неверный номер параметра: смешанные именованные и позиционные параметры».
Все та же проблема.
И еще один вариант, который использует ту же технику с функцией $ join-> on.
$tests->join('test_categories', function ($join) use ($category) {
$join->on('test_categories.id', '=', DB::raw("(select category_id
from test_category
join test_categories on test_category.category_id = test_categories.id
where test_category.test_id = tests.id
and test_categories.name = :category
limit 1)"),array('category' => $category));
});
Это приводит к преобразованию массива ErrorException (E_NOTICE) в строку:
protected function compileWheresToArray($query)
{
return collect($query->wheres)->map(function ($where) use ($query) {
return $where['boolean'].' '.$this->{"where{$where['type']}"}($query, $where);
})->all();
}