我有以下查询:
$sql = "SELECT u.id,
u.login
FROM AcmeBundle:Users u
WHERE 1 = 1";
在某些情况下,我想在SELECT clausule中使用其他东西,例如:
if($count == 1)
{
$sql = "SELECT COUNT(u.id)
FROM AcmeBundle:Users u
WHERE 1 = 1";
}
但是没有再次编写整个查询...在这个if条件中,我只想在早期定义的$ sql变量中替换SELECT clausule的内容......我该怎么做?
类似的东西:
if($count == 1)
{
$sql = str_replace("SELECT ...", "COUNT(u.id)", $sql);
}
答案 0 :(得分:2)
或者您可以使用HEREDOC语法并添加$select
变量。
$select = $count == 1 ? "COUNT(u.id)" : "u.id, u.login";
$sql = <<<SQL
SELECT {$select}
FROM AcmeBundle:Users u
WHERE 1 = 1
SQL;
答案 1 :(得分:0)
$sql = "FROM AcmeBundle:Users u WHERE 1 = 1";
if($count == 1) {
$beginning = "SELECT COUNT(u.id) ";
} else {
$beginning = "SELECT u.id, u.login ";
}
$query = $beginning . $sql;
希望你的意思是。
答案 2 :(得分:0)
您也可以使用QueryBuilder 像这样:
$builder = $manager->createQueryBuilder()
->select('p')
->from('AcmeDemoBundle:Product', 'p');
将导致SELECT p FROM AcmeDemoBundle:Product p;
如果你现在重置 SELECT
就像这样:
$builder->select('COUNT(p)');
这将导致此查询:SELECT COUNT(p) FROM AcmeDemoBundle:Product p;
;