The difference is that a whereHas executes one query on the primary connection (like you see in your raw query)
But the with and withCount execute a second query on the connection if your Employee model.
As written in the documentation:
Eloquent does not currently support querying for relationship existence across databases. The relationships must exist within the same database.
A way to work around it is to set the $table property on your Model that includes your database name.
class Employee extends Model
{
use HasFactory;
protected $connection = "mysql_2";
protected $table = 'mysql_2.employees';
public function corporate(): BelongsTo
{
return $this->belongsTo(Corporate::class);
}
}
Or if you need more customization (like a dynamic database) you can overwrite the getTable function.
class Employee extends Model
{
use HasFactory;
protected $connection = "mysql_2";
public function corporate(): BelongsTo
{
return $this->belongsTo(Corporate::class);
}
public function getTable()
{
// We ask the database name on the connection and prepare that for the table name with a . in between.
return DB::connection($this->connection)->getDatabaseName() '.'. parent::getTable();
}
}
mohinsandhi liked this reply
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community