假設有數據庫A (表a,b),和數據庫B(表c),獲取的主要內容在數據庫A中
$db_B = env('B');
a::leftJoin('a','a.ID','b.ID')->leftJoin($db_B.'.c','c.ID','a.ID')->get()->toArray();
說明:這里使用env函數,是獲取在.env配置文件中,你所配置的那個數據庫的別名,例如你給數據庫B配置了 DATABASE_B=B ,那么你就用env('DATABASE_B')來獲取即可。
主要是庫名.表名這種方式就可以跨庫連表
實現不同數據庫的模型進行關聯
假設模型Replenishment和模型Product要關聯,並且模型Replenishment和模型Product的表是在不同數據庫
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Replenishment extends Model
{
protected $fillable = ['g_code'];
public $table = 'replenishment';
protected $connection = "mm"; //config/database.php中的connections數組中的
public function product(){
$connection = 'mysql';//config/database.php中的connections數組中的
return $this->setConnection($connection)->belongsTo(Product::class,'g_code','code');//Product::class就是要關聯的模型,g_code和code是關聯字段 } }