php 在laravel模型中更改数据库连接

lsmd5eda  于 2023-06-21  发布在  PHP
关注(0)|答案(5)|浏览(135)

所以我使用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';
}

所以如果有人有任何想法,我会非常感激。

whitzsjs

whitzsjs1#

不同的模型可以有不同的数据库连接。因此,您的模型使用正常的默认连接-但您的'McibModel'模型可以使用另一个连接:

class McibModel extends Model {

    protected $connection= 'second_db_connection';

    protected $table = 'agencies';

}

然后在你的DB连接文件中-你会有这样的东西:

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'    => '',
        ),
    ),
uinbv5nw

uinbv5nw2#

在一种方式中,设置受保护的属性将始终将特定模型连接到数据库。

class MyModel extends Model {

     protected $connection = "second_db_connection";
}

在查询中,我喜欢这种方法...

(new MyModel())->on('second_db_connnection')->get();
gajydyqb

gajydyqb3#

我认为对于很多用例来说,在运行时像这样声明连接会很方便:

$McibModel = new McibModel();
$McibModel->setConnection('second_db_connection');
ruarlubt

ruarlubt4#

您可以像这样设置另一个连接:

$product= new Product();
$product->setConnection('another_connection');
jucafojl

jucafojl5#

我也需要为一个表这样做,这里是我为Laravel 8找到的最快的方法:

// config/database.php
'mysqllogs' => [
    'driver' => 'mysql',
    'url' => env('DATABASE_URL'),
    'host' => env('DB_LOGS_HOST', '127.0.0.1'),
    'port' => env('DB_LOGS_PORT', '3306'),
    'database' => env('DB_LOGS_DATABASE', 'forge'),
    'username' => env('DB_LOGS_USERNAME', 'forge'),
    'password' => env('DB_LOGS_PASSWORD', ''),
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_general_ci',
    'prefix' => '',
    'prefix_indexes' => true,
    'strict' => true,
    'engine' => null,
    'options' => extension_loaded('pdo_mysql') ? array_filter([
    PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
    ]) : [],
],

要访问新数据库,请执行以下操作:

Method 1:
DB::connection('mysqllogs')->statement('DELETE FROM logs where office_id=1');

Method 2:
$log = new Log();
.....
$log->setConnection('mysqllogs');
$log->save();

Method 3:
$logs = Log::on('mysqllogs')->where('office_id', 1);

相关问题