我想使用一个“中央”数据库和多个“客户”数据库(一个客户有1个DB)来创建应用程序。我想使用lumen rest api框架。 让我解释一下数据库背后的逻辑和我的问题。
中央数据库(简体):
表:租户
列: id(PK),id_tenant(FK),db_host,db_username,db_password,db_port,db_name
客户数据库(简体):
表格:问题
列: id(PK),id_creator,issue_name,write_time
我有两个模型: 房客
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
class Tenants extends Model implements AuthenticatableContract, AuthorizableContract
{
use Authenticatable, Authorizable;
protected $connection = 'mysql2';
protected $fillable = [
'id_tenant'
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
];
}
问题:
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
class Issues extends Model implements AuthenticatableContract, AuthorizableContract
{
use Authenticatable, Authorizable;
protected $connection = 'tenant';
protected $fillable = [
'id_issue'
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
];
}
此外,我已经在config / database.php中创建了文件:
<?php
return [
'default' => 'mysql',
'connections' => [
'mysql2' => [
'driver' => 'mysql',
'host' => 'dbhost',
'database' => 'dbName',
'username' => 'dbUser',
'password' => 'secretPass',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
'tenant' => [
'driver' => 'mysql',
'host' => '',
'port' => '',
'database' => '',
'username' => '',
'password' => '',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
]
],
]
?>
当我在config / database.php中将有关租户数据库的信息硬编码时,我已经编写了2个控制器(TenantsController和IssuesController),它们没有任何问题。
我的问题是:
当我呼叫路线时:api/tenant/1
(使用=> TenantsController @ getTenantById)
Lumen使用ID为1的请求租户的db数据返回正确的JSON。我需要将此数据填充到表问题所在的另一个(客户)数据库的连接变量。如何设置数据库连接“租户”以从第二个DB调用路由api/issues
并获取所有问题的列表?
注意:让我们从用户身份验证和安全API中抽象出来。
谢谢您的帮助。