Laravel 4:使用Eloquent连接多个数据库连接的两个表
对于多个数据库连接(例如主数据库、DB1、DB2、DB3等等),使用Eloquent连接两个表时,我面临一个问题。让我简单解释一下:- 假设我有两张桌子。类别和2。产品。两个表的型号如下:- 1) Category.php 类范畴扩展雄辩{Laravel 4:使用Eloquent连接多个数据库连接的两个表,laravel,laravel-4,Laravel,Laravel 4,对于多个数据库连接(例如主数据库、DB1、DB2、DB3等等),使用Eloquent连接两个表时,我面临一个问题。让我简单解释一下:- 假设我有两张桌子。类别和2。产品。两个表的型号如下:- 1) Category.php 类范畴扩展雄辩{ public $timestamps = false; protected $table = 'categories; protected $fillable = array('v_name','e_status'); public function p
public $timestamps = false;
protected $table = 'categories;
protected $fillable = array('v_name','e_status');
public function products()
{
return $this->belongsTo(Product,'i_category_id');
}
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');
}
}
2) Product.php
类积扩展雄辩{
public $timestamps = false;
protected $table = 'categories;
protected $fillable = array('v_name','e_status');
public function products()
{
return $this->belongsTo(Product,'i_category_id');
}
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之后,我们发现雄辩的ORM使用多个select查询而不是join查询
我们的概念是,我们有一个主数据库和从系统创建的其他动态数据库。我们需要连接多个数据库表以实现某些功能,但目前无法实现。我们不能用新的动态连接覆盖主数据库连接
我们能找到解决办法吗?另外,Laravel是否提供关闭/破坏先前连接并连接新数据库(如核心PHP)的功能
谢谢请在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\u dynamic\u connection=app/database.php中的另一个数据库连接,$objdataAuth->v\u db\u name=您的数据库连接名称
$objProduct = new Product;
$arrProductDetail = $objProduct->where('id','=',1)->first()->categories()->get();
echo '<pre>'; print_r($arrProductDetail);
$objProduct=新产品;
$arrProductDetail=$objProduct->where('id','=',1)->first()->categories()->get();
回声';打印(详细信息);
您将获得id为1的产品类别数组
谢谢,
莫南沙