Laravel 5 - 如何使用查询生成器或 Eloquent 在两个以上的表/查询中使用联合?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42616702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:28:32  来源:igfitidea点击:

Laravel 5 - How to use union in more than two tables/queries with Query Builder or Eloquent?

phplaravellaravel-5.3unions

提问by Fredy

I have 10 tables that i want 'union'. Here my table name with same fields.

我有 10 张桌子,我想要“联合”。这里我的表名具有相同的字段。

sell_2007
sell_2008
sell_2009
...
sell_2015
sell_2016

In the example given by laravel do union in the two tables only (https://laravel.com/docs/5.3/queries#unions), how if the table more than two tables/queries? In my case there are 10 tables. How to do that with Query Builder or Eloquent?

在 laravel 给出的例子中只在两个表中做联合(https://laravel.com/docs/5.3/queries#unions),如果表超过两个表/查询怎么办?就我而言,有 10 张桌子。如何使用 Query Builder 或 Eloquent 做到这一点?

Thank you for your help.

感谢您的帮助。

采纳答案by TedRed

You can add multiple unions like this;

您可以像这样添加多个联合;

$first = DB::table('sell_2007');
$second = DB::table('sell_2008');

$users = DB::table('users')
        ->union($first)
        ->union($second)
        ->get();

You may find that you get better perfomance to union the tables using RAW SQL query.

您可能会发现使用 RAW SQL 查询联合表可以获得更好的性能。