Laravel 从另一个项目数据库获取数据

2024-03-22

我正在将旧项目数据库移动到新项目数据库。旧项目数据库的结构是单个MYSQL数据库,新项目是包含很多子域的多租户数据库。此外,新项目已经设置了 RESTFUL API 来接收来自旧项目的数据。因此,我的想法是在新项目中实现多连接,以便将两个数据库链接在一起,然后从旧项目中获取数据。例如,新项目sales表是一个空的旧项目sales表已包含一些数据。现在,在我的新项目界面中可能有一个同步按钮,以便将数据从旧数据库移动到新数据库中。在将数据发送到新项目之前是否需要传递 API 密钥?因为它是多租户结构。

这是我的配置/数据库

'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'aurora-2016-cluster.cluster-rtygfdfg.ap-southwest-1.rds.amazonaws.com',
            'database'  => 'newProject',
            'username'  => @$_ENV['DB_USER'] ?: '',
            'password'  => @$_ENV['DB_PASS'] ?: '',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

        # Our secondary database connection
        'mysql2' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'oldProject',
            'username'  => 'root',
            'password'  => '',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

在 Laravel 中打开它非常简单config/databse.php file

你会发现这样的代码

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Database Connection Name
    |--------------------------------------------------------------------------
    |
    | Here you may specify which of the database connections below you wish
    | to use as your default connection for all database work. Of course
    | you may use many connections at once using the Database library.
    |
    */

    'default' => env('DB_CONNECTION', 'mysql'),

    /*
    |--------------------------------------------------------------------------
    | Database Connections
    |--------------------------------------------------------------------------
    |
    | Here are each of the database connections setup for your application.
    | Of course, examples of configuring each database platform that is
    | supported by Laravel is shown below to make development simple.
    |
    |
    | All database work in Laravel is done through the PHP PDO facilities
    | so make sure you have the driver for your particular database of
    | choice installed on your machine before you begin development.
    |
    */

    'connections' => [

        'sqlite' => [
            'driver' => 'sqlite',
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
            'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
        ],

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
        ],

        'pgsql' => [
            'driver' => 'pgsql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
            'schema' => 'public',
            'sslmode' => 'prefer',
        ],

        'sqlsrv' => [
            'driver' => 'sqlsrv',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '1433'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
        ],

    ],

    /*
    |--------------------------------------------------------------------------
    | Migration Repository Table
    |--------------------------------------------------------------------------
    |
    | This table keeps track of all the migrations that have already run for
    | your application. Using this information, we can determine which of
    | the migrations on disk haven't actually been run in the database.
    |
    */

    'migrations' => 'migrations',

    /*
    |--------------------------------------------------------------------------
    | Redis Databases
    |--------------------------------------------------------------------------
    |
    | Redis is an open source, fast, and advanced key-value store that also
    | provides a richer body of commands than a typical key-value system
    | such as APC or Memcached. Laravel makes it easy to dig right in.
    |
    */

    'redis' => [

        'client' => 'predis',

        'default' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => env('REDIS_DB', 0),
        ],

        'cache' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => env('REDIS_CACHE_DB', 1),
        ],

    ],

];

应遵循的步骤

步骤1: 将新数组添加到数据库连接数组

'mysqlSecondConnection' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST1', '127.0.0.1'),
            'port' => env('DB_PORT1', '3306'),
            'database' => env('DB_DATABASE2', 'secondDatabseName'),
            'username' => env('DB_USERNAME2', 'secondDatabseUserName'),
            'password' => env('DB_PASSWORD2', 'secondDatabsePassword'),
            'unix_socket' => env('DB_SOCKET2', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],

之后你的文件可能看起来像

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Database Connection Name
    |--------------------------------------------------------------------------
    |
    | Here you may specify which of the database connections below you wish
    | to use as your default connection for all database work. Of course
    | you may use many connections at once using the Database library.
    |
    */

    'default' => env('DB_CONNECTION', 'mysql'),

    /*
    |--------------------------------------------------------------------------
    | Database Connections
    |--------------------------------------------------------------------------
    |
    | Here are each of the database connections setup for your application.
    | Of course, examples of configuring each database platform that is
    | supported by Laravel is shown below to make development simple.
    |
    |
    | All database work in Laravel is done through the PHP PDO facilities
    | so make sure you have the driver for your particular database of
    | choice installed on your machine before you begin development.
    |
    */

    'connections' => [

        'sqlite' => [
            'driver' => 'sqlite',
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
            'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
        ],

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
        ],

        'mysqlSecondConnection' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST1', '127.0.0.1'),
            'port' => env('DB_PORT1', '3306'),
            'database' => env('DB_DATABASE2', 'secondDatabseName'),
            'username' => env('DB_USERNAME2', 'secondDatabseUserName'),
            'password' => env('DB_PASSWORD2', 'secondDatabsePassword'),
            'unix_socket' => env('DB_SOCKET2', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],


        'pgsql' => [
            'driver' => 'pgsql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
            'schema' => 'public',
            'sslmode' => 'prefer',
        ],

        'sqlsrv' => [
            'driver' => 'sqlsrv',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '1433'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
        ],

    ],

    /*
    |--------------------------------------------------------------------------
    | Migration Repository Table
    |--------------------------------------------------------------------------
    |
    | This table keeps track of all the migrations that have already run for
    | your application. Using this information, we can determine which of
    | the migrations on disk haven't actually been run in the database.
    |
    */

    'migrations' => 'migrations',

    /*
    |--------------------------------------------------------------------------
    | Redis Databases
    |--------------------------------------------------------------------------
    |
    | Redis is an open source, fast, and advanced key-value store that also
    | provides a richer body of commands than a typical key-value system
    | such as APC or Memcached. Laravel makes it easy to dig right in.
    |
    */

    'redis' => [

        'client' => 'predis',

        'default' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => env('REDIS_DB', 0),
        ],

        'cache' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => env('REDIS_CACHE_DB', 1),
        ],

    ],

];

步骤2:配置您的数据库名称mysqlSecondConnection array

IF THIS PROJECT IS TEAM COLLABRATING DONT FORGET TO ADD THE NEW ATTRIBUTES IN .ENV FILE

步骤3: 至此我们就完成了数据库的配置

步骤4: 打开需要与之交互的模型mysqlSecondConnection数据库

并添加

财产

protected $connection ='mysqlSecondConnection';

之后的模式可能看起来像例如: 我认为它是Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
/**
 * Class Cat
 *
 * @package App
*/

class Post extends Model
{


    /**
     * The connection name for the model.
     *
     * @var string
     */
    protected $connection ='mysqlSecondConnection';

    /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = ['id'];

     /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'posts';

    /**
     * The primary key for the model.
     *
     * @var string
     */

    protected $primaryKey = 'id';

    /**
     * The "type" of the auto-incrementing ID.
     *
     * @var string
     */
    protected $keyType = 'int';



    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name','title','desc'];

     /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [];

    /**
     * @var array
     */
    protected $dates = ['created_at','updated_at'];


}

这就是它的

现在是测试部分

打开路由文件夹中的 web.php 文件

并粘贴以下代码

Route::get('/testSecondConnection', function () 
{
    $posts= App\Post::all();
    dd($posts);

});

现在导航到yourApplication/testSecondConnection

现在看到connection被倾倒的财产

EDITED

我实际上忘记添加另一个方法是通过DB外观版本

只需将连接名称传递给DB在 - 的里面connection method

使用此功能时,不会检查型号

for the $connection财产在Post Model

$dbVersion = \DB::connection('mysqlSecondConnection')->table('posts')->get();
dd($dbVersion);

编辑为But which method is more efficient?

好问题伙计

情况一:

For Eg:

如果您正在使用mysqlSecondConnection为了Post然后对您项目的所有情况进行建模 将其添加到您的模型中

protected $connection ='mysqlSecondConnection';

这很好并且 笔记$connection物业将继续工作Eloquent not in DB Facade

情况2:

`Eg:'

如果您只使用很少的查询和调用mysqlSecondConnection

你不需要添加

protected $connection ='mysqlSecondConnection';

Post Model

DB Facade Version 

$dbVersion = \DB::connection('mysqlSecondConnection')->table('posts')->get();
    dd($dbVersion);

Eloquent Version

$eloquentVersion = Post::on('mysqlSecondConnection')->get()
    dd($eloquentVersion);

您可能会疑问为什么不使用 DB FACADEmysqlSecondConnection后模型中

解决方案:

在使用时DB FACADE

它将调查config/datbase.php

for default array

用于连接数据库

'default' => env('DB_CONNECTION', 'mysql'),

希望它有帮助并且看起来清晰

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Laravel 从另一个项目数据库获取数据 的相关文章

随机推荐

  • UITextView从底部开始

    我遇到了问题UI文本视图 我以前见过其他人也遇到过这个问题 但是每当我的应用程序在我的手机上加载时 所有UITextViews从文本的底部开始 我必须向上滚动 我已经尝试了多种解决方案 但我需要一个仅在情节提要上使用的解决方案 因为我有一些
  • dropzone.js 和 jquery 版本兼容性

    我最近在一些项目中使用 dropzone js 并配置选项没有问题 但在一个新项目中我使用的是由 Zend Framework 3 自动安装的最新版本的 jQuery 3 1 0 它似乎会导致一些问题与 dropzone js 版本 4 3
  • 如何在Tomcat(servlet容器)中监听套接字?

    我必须让网络应用程序监听套接字 服务器套接字 并处理套接字流 但该应用程序只是部署在 Tomcat 中 Tomcat 只是一个 servlet 容器 它没有 JCA 支持 并且在servlet线程中建立服务器套接字是不合理的 解决方案1 丑
  • ES6 中符号命名有约定吗?

    我正在摆弄 ES6 查看符号 与 Ruby 不同 例如你会写 symbol ES6符号似乎允许任何 标准 变量名 说实话 我觉得这很令人困惑 var privateProperty Symbol var obj obj privatePro
  • 我们应该在执行某些代码之前还是之后调用超类

    Android Studio 0 4 6 Hello 我这里有一个代码片段 我经常困惑 super 应该是第一行执行还是最后一行 通常 我将其作为第一次调用 以便可以在父类中设置默认属性 但是 我之前看过一些执行此操作的代码 我只是想知道这
  • Try Catch 无法与 PHP 中的 require_once 一起使用?

    我不能做这样的事吗 try require once includes functions php catch Exception e echo Message e gt getMessage echo Code e gt getCode
  • 如何在 Laravel 中使用 paginator::make() 在视图中显示结果集?

    我用过Paginator make对表中的记录进行分页 在视图中 我得到了分页链接 但每个链接都包含其中的所有记录 如何限制它perPage项目 datas Paginator make paginator count paginator
  • GCC中函数调用的参数求值顺序

    当我用谷歌搜索这个时 我总是得到关于评估顺序的线索 一般来说 评估顺序是未指定的 我知道参数评估顺序未指定C一般来说 我的问题是参数评估顺序gcc 从左到右还是从右到左 任何资源链接也将不胜感激 EDIT 消除问题中的歧义 嗯 我说的是当时
  • 使用配置文件添加 WSO2 IS Oauth / OpenId Connect 服务提供商

    我们目前在我们的环境中使用自动化流程 我们有 WSO2 5 3 0 我需要使用 XML 配置文件配置 Oauth2 Openid 服务提供程序 所有文档 示例等均面向 SAML2 而不是 Oauth2 OpenId 有人可以帮助我吗 目前您
  • 根据字符串长度过滤字符串数据

    我喜欢过滤掉字符串长度不等于10的数据 如果我尝试过滤掉其列的任何行A s or B的字符串长度不等于10 我尝试了这个 df pd read csv filex csv df A df A apply lambda x x if len
  • 如何在 Visual Studio 2017 Professional 中打开 ReactJS 项目

    我通过 create react app 和 yo office 命令创建了项目 https dev office com docs add ins excel excel add ins get started react https d
  • C++ 将ASII转义unicode字符串转换为utf8字符串

    我需要读取带有 unicode 转义的标准 ascii 样式字符串 并将其转换为包含 utf8 编码等效项的 std string 因此 例如 u03a0 具有 6 个字符的 std string 应转换为原始二进制文件中具有两个字符 分别
  • 将 Maven Java 编译器调试设置为 false 不会删除行号表?

    也许这是我缺乏理解 但我认为在 Maven Java 项目中执行此操作会禁用所有调试信息进入类文件
  • 为什么固定宽度元素不占用浮动元素旁边的空间?

    In this CodePen http codepen io nitinsavant pen qrvwQd the
  • Qt:以编程方式定义 Tab 键顺序

    我使用 Desinger 创建了 2 个小部件 Widget1 和 Widget2 每个小部件都定义了其 Tab 键顺序 第三个小部件 Widget3 以编程方式定义 并包含垂直布局中的上述 2 个小部件 在 symbian 非触摸设备上
  • C++ 中的舍入和往返数字

    我有一个类 它在内部将某个定点数表示为 32 位整数 分母有些任意 它既不是 2 的幂也不是 10 的幂 为了与其他应用程序通信 数量在输出时转换为普通的旧双精度 并在输入时转换回来 作为类内的代码 它看起来像 int32 t quanti
  • 如何在 C# 中从派生类实例调用基方法?

    我有 C 代码 基础class A并得出class B public class A public virtual void print Console WriteLine a public class B A public overrid
  • WinRT 反射 (C++/CX)

    如何内省 C CX 中的对象 我知道如何获取其类名 使用 IInspectable 但我无法弄清楚如何获取其属性列表 或者如果我只有方法名称 字符串 则如何调用方法 我在这里和 Google 中搜索了答案 但我发现与 WinRT 的 NET
  • 使用 COUNT 显示 MySQL 中出现次数超过 2 次的不同记录

    我有一个表 我试图在其中构建表中出现两次以上的所有城市的不同列表 我正在尝试当前查询 我被告知 函数计数不存在 我究竟做错了什么 SELECT COUNT city FROM table1 GROUP BY city HAVING COUN
  • Laravel 从另一个项目数据库获取数据

    我正在将旧项目数据库移动到新项目数据库 旧项目数据库的结构是单个MYSQL数据库 新项目是包含很多子域的多租户数据库 此外 新项目已经设置了 RESTFUL API 来接收来自旧项目的数据 因此 我的想法是在新项目中实现多连接 以便将两个数