简体   繁体   中英

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 

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::

我知道您提到过要使用查询生成器,但是对于该生成器可能适合的复杂查询,您可以直接访问PDO对象:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM