I have two models, one mongo model extending the Jenssegers \ Model and another sql model extending the Illuminate \ Model. This sql model does not have a connection name defined as ours with several database connections that have the same table in each database.
Mongo Model Comment.php
<?php namespace App\Models\Mongo; use Jenssegers\Mongodb\Eloquent\Model as Eloquent; class Comment extends Eloquent { protected $connection = 'mongodb'; protected $collection = 'comments'; public $timestamps = true; protected $dateFormat = 'Ymd H:i:s'; public function userProfile() { return $this->belongsTo('\\App\\Models\\Sql\\UserDefaultProfile', 'created_by', 'user_code'); } }
Sql Model UserProfile.php
<?php namespace App\Models\Sql; use Illuminate\Database\Eloquent\Model; use Jenssegers\Mongodb\Eloquent\HybridRelations; class UserDefaultProfile extends Model { use HybridRelations; protected $table = 'user_default_profile'; public $timestamps = false; }
I have several database connections, add to 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); } }
therefore several database connections are available
Now the problem is that I caused eloquence with attitude, I get Database [Default] not configured . I get this error because the UserProfile Model has no specific connection. So, please, someone who can tell how to pass the name of the connection to the relationship model.
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(); }
So is it possible to do something similar with an attitude
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();