Al_
Al_

Reputation: 2509

Laravel using UNION in query builder

I have an SQL query that works fine and I'm trying to convert into fluent::

SELECT DISTINCT tags.tag
  FROM tags, items
  WHERE tags.taggable_type = 'Item'
  AND items.item_list_id = '1'
UNION
SELECT DISTINCT tags.tag
  FROM tags, itemlists
  WHERE tags.taggable_type = 'ItemList'
  AND itemlists.id = '1'

This is what I have so far in fluent, it all seems right as far as I can tell from the docs and the individual queries both work on their own, it's just when I UNION them it throws an error:

   $itemTags = Tag::join('items', 'items.id', '=', 'tags.taggable_id')
                ->select('tags.tag')
                ->distinct()
                ->where('tags.taggable_type', '=', 'Item')
                ->where('items.item_list_id', '=', $itemList->id);

    $itemListTags = Tag::join('itemlists', 'itemlists.id', '=', 'tags.taggable_id')
                ->select('tags.tag')
                ->distinct()
                ->where('tags.taggable_type', '=', 'ItemList')
                ->where('itemlists.id', '=', $itemList->id);
// the var_dump below shows the expected results for the individual queries
// var_dump($itemTags->lists('tag'), $itemListTags->lists('tag')); exit;
    return      $itemTags
                ->union($itemListTags)
                ->get();

I get the following error when I run it (I've also swapped from Ardent back to Eloquent on the model in case that made a difference - it doesn't):

Argument 1 passed to Illuminate\Database\Query\Builder::mergeBindings() must be an instance of Illuminate\Database\Query\Builder, instance of LaravelBook\Ardent\Builder given, called in path/to/root\vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php on line 898 and defined 

Upvotes: 1

Views: 11986

Answers (2)

Uze
Uze

Reputation: 173

I know you mentioned wanting to use the query builder, but for complex queries that the builder might throw fits on, you can directly access the PDO object:

$pdo = DB::connection()->getPdo();

Upvotes: 1

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87719

Looks like your models are using Ardent, not Eloquent:

...instance of LaravelBook\Ardent\Builder given, ...

And probably this might be a problem on Ardent, not Laravel.

Open an issue here: https://github.com/laravelbook/ardent.

EDIT:

Try to change use QueryBuilder instead of Eloquent:

Use this for QueryBuilder:

DB::table('tags')->

Instead of the Eloquent way:

Tag::

Upvotes: 4

Related Questions