一般错误:2031联合两个查询时(laravel datatables)

时间:2017-07-04 09:43:18

标签: php sql laravel datatables

这些是构成要推送到laravel数据表构建器的集合的查询:

foreach (Session::get('trienios') as $trienio) {
    $oeTrienios = $oeTrienios->where('data_trienio', $trienio->trienio)->whereHas('curso', function ($query) use ($trienio) {
        $query->where('curso', $trienio->curso);
    });
}

$union = Trienio::with('curso')->whereHas('curso', function ($query) use ($coordinatedCourse) {
    $query->where('curso', $coordinatedCourse);
})->union($oeTrienios);


$trienios = \DB::table(\DB::raw("({$union->toSql()}) as x"))->select(['data_trienio']);

官方laravel-datatables网站上有一个教程“解释”如何使用统一查询,但是它非常模糊,无法实际解释任何内容,此外,当我尝试添加代码时在教程上:

$trienios = \DB::table(\DB::raw("({$union->toSql()}) as x"))

它给了我以下错误:

SQLSTATE[HY000]: General error: 2031 (SQL: select count(*) as aggregate from (select `data_trienio` from ((select * from `trienios` where exists (select * from `cursos` where `trienios`.`curso_id` = `cursos`.`id` and `curso` = ?)) union (select * from `trienios` where `data_trienio` = ? and exists (select * from `cursos` where `trienios`.`curso_id` = `cursos`.`id` and `curso` = ?) and `data_trienio` = ? and exists (select * from `cursos` where `trienios`.`curso_id` = `cursos`.`id` and `curso` = ?))) as x) count_row_table)

但是,如果我将参数->get()附加到->union($oeTrienios),它将正常工作,但是,数据集上的集合将无法解析。

如何解决此问题?任何帮助都会非常受欢迎。

P.S - 演示链接:https://datatables.yajrabox.com/fluent/union

1 个答案:

答案 0 :(得分:2)

子查询$union->toSql()只有没有参数的sql代码,需要调用bindings。请参阅here,代码为:

$trienios = \DB::table(\DB::raw("({$union->toSql()}) as x"))
    ->select(['data_trienio'])
    ->mergeBindings($union);