Laravel 4:连接来自不同数据库的表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21519170/
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 08:57:37  来源:igfitidea点击:

Laravel 4: Join tables from different database

phpmysqllaravellaravel-4jointable

提问by ally

I have a project that connects with different database, and i want to join those tables from different database using laravel 4. I searched already about this issue but i can't find the right answer. Is it possible to join tables from different database in laravel 4? If possible,does anyone can help me how to build a query for that?

我有一个连接不同数据库的项目,我想使用 laravel 4 连接来自不同数据库的那些表。我已经搜索过这个问题,但我找不到正确的答案。是否可以在laravel 4中连接来自不同数据库的表?如果可能,有人可以帮助我如何为此构建查询吗?

回答by Morgon

You can do exactly that using the DB class:

您可以使用DB 类完全做到这一点:

$results = DB::select('select * from database1.users u1 LEFT JOIN database2.users u2 ON u1.id = u2.id WHERE u2.id = ?', array(5));

You can also use Fluentto build the query, which would look something like:

您还可以使用Fluent来构建查询,它类似于:

$users = DB::table('db1.users as db1')
  ->select('db1.*')
  ->leftJoin('db2.users as db2', 'db1.id', '=', 'db2.id')
  ->where('db2.id', 5)
  ->get();