douma5954 2018-09-11 14:38
浏览 590
已采纳

Laravel,为一种方法更改模型中的连接?

I have got a dev database and a live database. I need to return some results from the live database but only for one method within this model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class TableName extends Model
{
    protected $table = 'table_name';

    protected $connection = 'dev';

    public $timestamps = false;

    public static function live($index) {

        $liveId = Settings::where('index', $index)->get()[0];

        $live = new TableName;

        $live->setConnection('live');

        $data = $live::where('index', $liveId->live_index)->get();

        dd($live);

        return $data;

    }
}

If I dd() the $live variable after calling setConnection then it does say that the connection is indeed live. However as soon as I dd() the $data I get the rows from the dev database!

  • 写回答

3条回答 默认 最新

  • douxuanwei1980 2018-09-11 14:50
    关注

    Eloquent provides a nice way to handle multiple connections.

    You should just be able to use the on method. For example.

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class TableName extends Model
    {
        protected $table = 'table_name';
    
        protected $connection = 'dev';
    
        public $timestamps = false;
    
        public static function live($index) {
    
            $liveId = Settings::where('index', $index)->get()[0];
    
            $data = self::on('live')->where('index', $liveId->live_index)->get();
    
            return $data;
    
        }
    }
    

    That should then run the query using the live connection in your database configuration.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?