这些是我的模特
class Posts extends Model {
protected $connection = 'connection_1';
public function comments()
{
$model = new Comments();
$model->setConnection($this->connection);
return $this->hasMany($model, 'comments_id');
}
}
class Comments extends Model {
protected $connection = 'connection_1';
public function author()
{
$model = new Authors();
$model->setConnection($this->connection);
return $this->hasOne($model, 'id', 'authors_id');
}
public function post()
{
$model = new Posts();
$model->setConnection($this->connection);
return $this->hasOne($model, 'id', 'posts_id');
}
}
class Authors extends Model {
protected $connection = 'connection_1';
public function comments()
{
$model = new Comments();
$model->setConnection($this->connection);
return $this->hasMany($model, 'authors_id');
}
}
当我将这段代码放入控制器时,注释模型已连接到connection_2,但是Authors为空,我想它并没有改变与connection_2的连接
$posts = new Posts;
$posts->setConnection('connection_2');
$posts->load("comments.author")->get();
我如何从动力学上更改Authors模型的连接,或为什么Authors为空?
我已经解决了这样的问题:
$conn = \App\Helpers\Helper::connection($item_id);
$newPdo = \DB::connection($conn)->getPdo();
\DB::setPdo($newPdo);
$posts = \App\Posts::with("comments.author")->get();
还有我的助手
public static function connection($project) {
switch($project) {
case 01:
return 'connection_01';
break;
case 02:
return 'connection_02';
break;
case 03:
return 'connection_03';
break;
}
}