0

How do I run this simple Mysql query in Laravel, from two different databases?

SELECT * FROM database1.table1, database2.table2

And how I do joins in Eloquent on different databases?

3
  • laravel.com/docs/5.3/queries#joins Commented Nov 30, 2016 at 17:39
  • Hackerman - Multiple Databases? I dont think so... Commented Nov 30, 2016 at 17:47
  • 1
    If the databases are on the same server and the mysql user has access to both databases, you should be able to do it without any issues. You may just need to use DB::raw Commented Nov 30, 2016 at 17:51

2 Answers 2

4

As I mentioned, if the databases are on the same server and the mysql user has access to both databases, you can pass the tables in with DB::raw:

$q1 = DB::table(DB::raw('database1.table1 AS db1_tb1'))->select('*');
$results = DB::table(DB::raw('database2.table2 AS db2_tb2'))->select('*')
->union($q1)
->get();

For a join:

DB::table(DB::raw('database1.table1 AS db1_tb1'))
   ->join(DB::raw('database2.table2 AS db2_tb2'),'db1_tb1.first_key','=','db2_tb2.second_key')
Sign up to request clarification or add additional context in comments.

Comments

3

You cannot use different connections to do that, so you should do something like:

$result = DB::connection('database1')->table('contacts')->get()
            ->union(
                DB::connection('database2')->table('contacts')->get()
            );

And if your Query Builder is does not return collections:

$result = collect(DB::connection('database1')->table('contacts')->get())
            ->union(
                collect(DB::connection('database2')->table('contacts')->get())
            );

1 Comment

Ok, thanks! And how to do JOIN in multi databases? Just manually?

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.