laravel使用模型实现跨库连表

假设有数据库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 AppModels;

use IlluminateDatabaseEloquentModel;

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是关联字段    } }
原文地址:https://www.cnblogs.com/caibaotimes/p/14022489.html