如何告诉"whereHas"查询子查询表在另一个数据库中(多租户)



我使用Laravel tenancy - multi-tenant库使我的应用程序成为多租户,因为每个组织都应该有自己的数据库。只要它能自动识别在正确的数据库中搜索用户的租户,这就可以很好地工作。

例如,当我尝试执行whereHas查询时,如:

// hostname is a system db table
$userQuery = User::query();  // This is a tenant db table
$userQuery->whereHas('hostname', function ($q) {
$q->where('id', 1);
});
$users = $userQuery->get();

雄辩地在与users表相同的数据库中搜索hostnames表。

错误

Illuminate/Database/QueryException with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table '721d9894276846dbb20d36ff83c46fb3.hostnames' doesn't exist (SQL: select * from `users` where exists (select * from `hostnames` where `users`.`hostname_id` = `hostnames`.`id` and `id` = 1 and `hostnames`.`deleted_at` is null))'

以下关系很好:

Username::first()->hostname

User.php

<?php
namespace App;
use HynTenancyAbstractsTenantModel;
class User extends TenantModel
{
public function hostname() { return $this->belongsTo('AppHostname'); }
}

主机名.php

<?php
namespace App;
use HynTenancyTraitsUsesSystemConnection;
class Hostname extends HynTenancyModelsHostname
{
public function user() { return $this->hasMany('AppUser', 'hostname_id'); }
}

注意,这个用户-主机名关系只是一个例子。对于使用2个数据库中的表的每个whereHas查询,我都会遇到同样的问题。

我如何"告诉"whereHas查询另一个数据库中的相关表?我只在whereHas查询中遇到过这个问题(至少目前,没有尝试所有可能的查询类型(

我建议创建一个新的UsesTantanConnection,在其中建立一个新函数,返回租户数据库的表名

要做到这一点,您必须在"app/Trats/UsesTenantConnection.php">

<?php
namespace AppTraits;
use HynTenancyDatabaseConnection;
trait UsesTenantConnection
{
public function getConnectionName()
{
return app(Connection::class)->tenantName();
}
public function getTable(): string
{
$config = app(HynTenancyDatabaseConnection::class)->configuration();
if (str_starts_with(parent::getTable(), $config['database']))
return parent::getTable();
return "{$config['database']}." . parent::getTable(); // TODO: Change the autogenerated stub
}
}

最新更新