【问题标题】:Laravel 4: Joining two tables using Eloquent for multiple database connectionsLaravel 4:使用 Eloquent 连接两个表以进行多个数据库连接
【发布时间】:2014-10-11 04:13:46
【问题描述】:

我在使用 Eloquent 连接两个表进行多个数据库连接(例如主数据库、DB1、DB2、DB3 等)时遇到问题。让我在下面简要解释一下:-

假设,我有两个表 1. 类别和 2. 产品。两个表的型号如下:-

1) 分类.php

类 Category 扩展 Eloquent{

public $timestamps = false;

protected $table = 'categories;
protected $fillable = array('v_name','e_status');

public function products()
{
    return $this->belongsTo(Product,'i_category_id');
}

}

2) 产品.php

类产品扩展了 Eloquent{

public $timestamps = false;

protected $table = products;
protected $fillable = array('v_name',’i_category_id’,'e_status');

public function categories()
{
    return $this->belongsTo(Category,'i_category_id');
}

}

现在,在 ProductController.php 中

$objProduct = new Product; 
$objProduct->setDBConnection($objdataAuth->v_db_name);  // dynamic database connection name
$arrProductDetail = $objProduct->get()->section_activities()->get();

$arrProductDetail 不检索与类别相关的信息(即动态数据库)。但是,它检索主数据库的类别(即在 app/database.php 中)。 如果我们只取 $objProduct->get() 那么它将检索新数据库的所有产品(DB1,DB2 ....) 但是经过一些 rnd 我们发现 eloquent ORM 使用多个选择查询而不是连接。

我们的概念是我们有一个主数据库和另一个从系统创建的动态数据库。我们需要为某些功能连接多个数据库表,而我们现在还不能。我们不能用新的动态连接覆盖主数据库连接。

我们有什么解决办法吗? Laravel 是否还提供关闭/销毁先前连接并连接新 DB(如 Core PHP)的功能?

谢谢

【问题讨论】:

    标签: laravel laravel-4


    【解决方案1】:

    请在 app/database.php 中添加以下代码

    'mysql_dynamic_connection' => array(
                'driver'    => 'mysql',
                'host'      => 'host',
                'database'  => 'db_name',
                'username'  => 'username',
                'password'  => 'password',
                'charset'   => 'utf8',
                'collation' => 'utf8_unicode_ci',
                'prefix'    => '',
            ),
    

    现在,在模型产品和类别中添加以下行,

    protected $connection = 'mysql_dynamic_connection';
    

    现在,将控制器文件中的数据库连接设置为

    Config::set('database.connections.mysql_dynamic_connection.database', $objdataAuth->v_db_name);
    

    其中 mysql_dynamic_connection = app/database.php 中的另一个数据库连接和 $objdataAuth->v_db_name = 您的数据库连接名称

    $objProduct = new Product; 
    $arrProductDetail = $objProduct->where('id','=',1)->first()->categories()->get();
    echo '<pre>'; print_r($arrProductDetail);
    

    你会得到id为1的product的category数组。

    谢谢, 莫南沙阿

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-22
      • 2013-05-17
      • 1970-01-01
      • 2019-08-11
      • 2019-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多