【问题标题】:How to change connection of eager loading?如何更改急切加载的连接?
【发布时间】:2020-05-09 05:11:15
【问题描述】:

这些是我的模型

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 但作者为空,我猜它不会更改与 connection_2 的连接

$posts = new Posts;
$posts->setConnection('connection_2');
$posts->load("comments.author")->get();

如何动态更改 Authors 模型连接,或者为什么 Authors 为空?

【问题讨论】:

    标签: laravel eager-loading


    【解决方案1】:

    我已经这样解决了我的问题:

    $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;
        }
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-07
      • 2020-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-09
      相关资源
      最近更新 更多