我有两个模型,一个是扩展 Jenssegers\Model 的 mongo 模型,另一个是扩展 Illuminate\Model 的 sql 模型。此 sql 模型没有定义连接名称,因为我们有多个数据库连接,每个数据库中都有相同的表。
Mongo 模型 Comment.php
<?php
namespace App\Models\Mongo;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Comment extends Eloquent
{
/** @var string Mongo Connection Name */
protected $connection = 'mongodb';
/** @var string Mongo Collection Name */
protected $collection = 'comments';
/** @var bool Enable/Disable Timestamp */
public $timestamps = true;
/** @var date Date format */
protected $dateFormat = 'Y-m-d H:i:s';
public function userProfile()
{
return $this->belongsTo('\\App\\Models\\Sql\\UserDefaultProfile', 'created_by', 'user_code');
}
}
Sql 模型 UserProfile.php
<?php
namespace App\Models\Sql;
use Illuminate\Database\Eloquent\Model;
use Jenssegers\Mongodb\Eloquent\HybridRelations;
class UserDefaultProfile extends Model
{
use HybridRelations;
/** @var string Table Name */
protected $table = 'user_default_profile';
/** @var bool Enable/Disable Timestamp */
public $timestamps = false;
}
我有多个数据库连接添加到 Capsule
try {
$getDatabaseList = StoreDatabaseCredential::all();
} catch (Exception $exception) {
}
foreach ($getDatabaseList as $database) {
if (strtolower($database->database_type) == 'mysql') {
$db->addConnection([
'driver' => 'mysql',
'host' => $database->database_router_read_host,
'port' => $database->database_router_read_port,
'database' => $database->database_name,
'username' => $database->database_user,
'password' => $database->database_password,
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
'prefix' => '',
], $database->connection_name);
}
}
因此可以使用多个数据库连接
现在的问题是当我用关系称雄辩时,我得到了Database [Default] not configured
。我收到此错误是因为 UserProfile 模型没有定义任何连接。所以,请谁能告诉如何将连接名称传递给关系模型。
try {
$comments = Comment::where([
'in_reply_to_content_id' => $contentId,
'super_store_id' => $superStoreId,
'is_deleted' => 0
])->with([
'userProfile' => function ($query) use ($dbConnectionName) {
$query->select('id', 'user_code', 'mobile', 'name', 'profile_pic_url');
}
])->skip($offset)->take($itemsPerPage)->orderBy('created_at', 'desc')->get();
Utils::printData($contentComments);
exit();
} catch (\Throwable $exception) {
Utils::printData($exception->getMessage());
exit();
}
那么,是否有可能对关系做这样的事情
with([
'userProfile' => function ($query) use ($dbConnectionName) {
$query->setConnection($dbConnectionName)->select(
'id', 'user_code', 'mobile', 'name', 'profile_pic_url'
);
}
])->skip($offset)->take($itemsPerPage)->orderBy('created_at', 'desc')->get();