Laravel,用一种方法更改模型中的连接? [英] Laravel, change connection in model for one method?
问题描述
我有一个dev数据库和一个实时数据库.我需要从实时数据库中返回一些结果,但仅需要此模型中的一种方法.
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;
}
}
如果在调用setConnection
之后我dd()
$live
变量,那么它确实表示该连接确实是live
.但是,一旦我dd()
$data
,我就会从 dev 数据库中获得行!
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!
推荐答案
口才提供了一种处理多个连接的好方法.
Eloquent provides a nice way to handle multiple connections.
您应该只能使用on
方法.例如.
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;
}
}
然后应该使用数据库配置中的live
连接来运行查询.
That should then run the query using the live
connection in your database configuration.
这篇关于Laravel,用一种方法更改模型中的连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!