2

Those are the queries that form the collection to be pushed to the laravel datatables builder:

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']);

There is a tutorial on the official laravel-datatables site that "explains" how to work with united queries, however it is pretty vague and can't realistically explain anything, and besides, when I tried to add a code they had on the tutorial:

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

It gives me the following error:

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)

If I, however, attach the parameter ->get() to the ->union($oeTrienios), it will work just fine, however, the collection will come unorderable on the datatable.

How do I solve this issue? Any help would be very welcome.

P.S - Link to the demo: https://datatables.yajrabox.com/fluent/union

2
  • Can you please mention link to the tutorial for uniting queries? Commented Jul 4, 2017 at 9:49
  • added to the post. Commented Jul 4, 2017 at 9:50

1 Answer 1

3

The subquery $union->toSql() has only sql code without parameters and you need call bindings. See here and code will be:

$trienios = \DB::table(\DB::raw("({$union->toSql()}) as x"))
    ->select(['data_trienio'])
    ->mergeBindings($union);
Sign up to request clarification or add additional context in comments.

2 Comments

throws this error: Argument 1 passed to Illuminate\Database\Query\Builder::mergeBindings() must be an instance of Illuminate\Database\Query\Builder, instance of Illuminate\Database\Eloquent\Builder given.
I think $union should be $union->getQuery(). Whatever, this one saved my life.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.