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 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型