Moh*_*sar 12 php laravel laravel-4
所以我使用Laravel 4.2,我想要的是在我的一个模型中使用外部数据库,这是我的模型代码:
<?php
class McibModel extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
//here i should call the external database table
protected $table = 'agencies';
}
Run Code Online (Sandbox Code Playgroud)
所以,如果有人有任何想法,我将非常感激.
Lau*_*nce 28
不同的模型可以有不同的数据库连接 所以你的模型使用普通的默认连接 - 但你的'McibModel'模型可以使用另一个连接:
class McibModel extends Model {
protected $connection= 'second_db_connection';
protected $table = 'agencies';
}
Run Code Online (Sandbox Code Playgroud)
然后在你的数据库连接文件中 - 你会有这样的东西:
return array(
'connections' => array(
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database1',
'username' => 'user1',
'password' => 'pass1'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
'second_db_connection' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database2',
'username' => 'user2',
'password' => 'pass2'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
),
Run Code Online (Sandbox Code Playgroud)
以一种方式设置受保护的属性将始终将特定模型连接到数据库。
class MyModel extends Model {
protected $connection = "second_db_connection";
}
Run Code Online (Sandbox Code Playgroud)
在查询中,我喜欢这种方法......
(new MyModel())->on('second_db_connnection')->get();
Run Code Online (Sandbox Code Playgroud)
我认为对于很多用例来说,像这样在运行时声明连接会很方便:
$McibModel = new McibModel();
$McibModel->setConnection('second_db_connection');
Run Code Online (Sandbox Code Playgroud)