我正在尝试使子查询类似
SELECT COUNT (*) as total_count FROM ($sql) as count_table
此处是方法:
public function getTotal($query = null)
{
if (is_null($query)) {
return $this->total;
}
$sql = $query->toSql();
$bindings = $query->getBindings();
foreach ($bindings as $binding) {
$bind = gettype($binding) === '' ? "'" . $binding . "'" : $binding; //is not working as expected
$sql = preg_replace('/\?/', $bind, $sql, 1);
}
dd($sql);
$sql = str_replace('\\', '\\\\', $sql);
$total = \DB::connection('sqlsrv')->select(\DB::raw("select count(*) as total_count from ($sql) as count_table"));
return $total[0]->total_count;
}
问题是当我preg_replace all吗?在sql查询中,我只获得没有数据类型的值。
我的getBindings():
array:14 [▼
0 => 0
1 => "D"
2 => 0
3 => 0
4 => "CZ"
5 => "00000"
6 => "15000"
7 => "D"
8 => 0
9 => 0
10 => 0
11 => "AT"
12 => "0000"
13 => "2000"
]
在此数组中,我有一些整数和字符串,我想绑定完全相同的数据类型。
我试图用gettype()检查字符串,但这不起作用。
答案 0 :(得分:0)
在Laravel 5.6.12中,fromSub()
函数已添加到查询生成器中,该函数可以完成您要执行的操作。
未经测试,但我认为您的函数应类似于:
public function getTotal($query = null)
{
if (is_null($query)) {
return $this->total;
}
return \DB::connection('sqlsrv')
->selectRaw('count(*) as total_count')
->fromSub($query)
->value('total_count');
}
如果尚未使用5.6.12,则可以完全使用selectRaw
语句来处理您的特定查询,该语句将绑定作为第二个参数。在这种情况下,您的函数将类似于:
public function getTotal($query = null)
{
if (is_null($query)) {
return $this->total;
}
return \DB::connection('sqlsrv')
->selectRaw('count(*) as total_count from ('.$query->toSql().') as count_table', $query->getBindings())
->value('total_count');
}
注意:如果您之前从未见过,则value()
函数将执行查询,获取第一行,然后从该第一行获取指定列的值。比使用get()
或first()
然后访问属性要干净一点。