Laravel中跨库关联模型可以使用数据库连接来实现。具体步骤如下:

  1. config/database.php文件中定义数据库连接信息,如下所示:
'connections' => [
    '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', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],
    'other_db' => [
        'driver' => 'mysql',
        'host' => env('OTHER_DB_HOST', '127.0.0.1'),
        'port' => env('OTHER_DB_PORT', '3306'),
        'database' => env('OTHER_DB_DATABASE', 'forge'),
        'username' => env('OTHER_DB_USERNAME', 'forge'),
        'password' => env('OTHER_DB_PASSWORD', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],
],
  1. 在模型中定义数据库连接信息,如下所示:
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The connection name for the model.
     *
     * @var string
     */
    protected $connection = 'mysql';

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

在以上代码中,$connection属性定义了使用的数据库连接,$table属性定义了使用的表名。

  1. 在关联模型中定义数据库连接信息,如下所示:
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function comments()
    {
        return $this->hasMany('App\Models\Comment', 'post_id')
                    ->onConnection('other_db');
    }
}

在以上代码中,onConnection()方法定义了关联模型所使用的数据库连接。

这样就可以实现跨库关联模型了。

Laravel跨库关联模型教程:轻松实现多数据库交互

原文地址: https://www.cveoy.top/t/topic/nbX4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录