问题描述
在项目中我需要连接、操作多个数据库的相同表,如何只建立一个orm模型,实现多个数据库的动态连接
问题出现的环境背景及自己尝试过哪些方法
我知道\DB::connection()可以指定,但是里面的方法没有orm里面的好用,所以想寻找更方便快捷的办法。
尝试:
我试过实例化model的时候传connection过去,(代码如下),但是这样的方式,create()、insert()等方法不适用,适用这些方法我动态指定的数据没作用,链接的是默认的数据库
相关代码
// 请把代码文本粘贴到下方(请勿用图片代替代码)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class TempModel extends Model
{
protected $table = 'temp';
protected $primaryKey = 'id';
protected $guarded = [];
protected $dateFormat = 'U';
public function __construct(array $attributes = [])
{
$this->connection = $attributes['connection'];
parent::__construct($attributes);
}
}
//使用,这样是可以动态指定的
$model = new TempModel(['connection'=>'define_db']);
$model->where('id',2)->first();
你期待的结果是什么?实际看到的错误信息又是什么?
但是如果使用$model->create() 等方法,就链接的时候默认的数据库配置不是我实例化传过去的,我使用
self::setConnection('define_db');
$this->setConnection('define_db');设置都不行。
protected $connection = 'define_db';
不知道你是不是想要这样的。