Union queries from different databases in Laravel Query Builder

只愿长相守 提交于 2019-12-30 05:28:05

问题


I have two similar tables in two different databases. Both tables have a column with a date and one with email addresses. Though the column names are not the same. As result I want to have one result that contains all records from both tables.

So my first step is:

$emails_1 = DB::connection('db1')->table('contacts_1')->select('mail_address AS email', 'date as created_at');
$emails_2 = DB::connection('db2')->table('contacts_2')->select('email', 'created_at');

So now I have two results and the column names in the result are equal (email and created_at).

Now I want to merge the results together, so I do:

$all_emails = $emails_1->union($emails_2);

And this is where I get the error:

Base table or view not found: 1146 Table 'db1.contacts_2' doesn't exist (SQL: (select mail_address as email, date as created_at from contacts_1) union (select email, created_at from contacts_2))

So it seems that query builder gets confused with the diferente tables.

Has anyone help?


回答1:


You can't use different connections, but you still can do it providing the db name explicitly:

$q1 = DB::table('db1.contacts')
       // where(..) or anything you need here
       ->select('mail_address as email', 'date as created_at');

$q2 = DB::table('db2.contacts')
       // like above
       ->select('email', 'created_at');

$result = $q2->union($q1)->get();



回答2:


You cannot do a UNION query across connections. You'll have to do it as two separate queries:

$emails1 = DB::connection('db1')->table('contacts_1')
             ->selectRaw('mail_address as email, date as created_at')->get();

$emails2 = DB::connection('db2')->table('contacts_2')
             ->select('email', 'created_at')->get();

$emails = array_merge($emails1, $emails2);


来源:https://stackoverflow.com/questions/27194651/union-queries-from-different-databases-in-laravel-query-builder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!